Friday, June 17, 2005

Why wait() and notify() should be inside a synchronized block?

I always wondered why does the Java language mandate that wait() should be kept inside a synchronized block. (Especially bcoz wait() releases the lock of the object immediately)

This is required by the language, and ensures that wait and notify are properly serialized. In practical terms, this eliminates race conditions that could cause the "suspended" thread to miss a notify and remain suspended indefinitely.

No comments:

Post a Comment