« The hidden costs of lazy fetch with AJAX | Main | Autistic or not? »

April 24, 2006

Coding wait in Java correctly

As Cameron pointed out in his blog last week, the docs for the wait method in Java were modified in Java 5 to indicate that wait can return for no reason, or you can be woken up spuriously. Apparently, this update doesn't indicate a behaviour change, it's always been like this. It's also a consistent behavior with whats specified in the POSIX specs for native pthread libraries.

Java code which uses monitors in a safe manner should not be affected by spuriousness. This means that wait must be called inside of a loop where some condition is being tested. Code which uses wait without a loop may be affected by spuriousness, but is also prone to undesirable race conditions.

Basically, if you call wait, you need to call it in a loop and test a variable when you wake up to make sure it was your notify or notifyAll which did the waking and not some implementation issue.

April 24, 2006 | Permalink


TrackBack URL for this entry:

Listed below are links to weblogs that reference Coding wait in Java correctly:


Can you give Cameron's blog address ?

Posted by: | Apr 25, 2006 4:17:58 AM

Cameron's blog: http://www.jroller.com/page/cpurdy

Posted by: Pete McKinstry | Apr 25, 2006 11:09:34 AM

Post a comment