[concurrency-interest] Re: spurious wakeups semantics (morehistory & refs)

David Holmes dholmes at dltech.com.au
Sun Nov 6 19:35:02 EST 2005


Pete Soper wrote:
> Bug 4777391 "unexpected behaviour of Object.wait method" came before the
> spec update but shows an extreme case of not having a condition ("test
> should be hung !!!" is printed due to a notify by the system).
>
> public class hang extends Thread {
>     public static void main(String argv[]) {
>         Thread thread = new hang();
>
>         System.out.println("prepare to hang !!");
>         try {
>             synchronized (thread) {
>                 thread.start();  /*1*/
>     	        thread.wait();   /*2*/
>             }
>
>             System.out.println("test should be hung !!!");
>         } catch (InterruptedException e) {
>             System.out.println("InterruptedException" + e);
>         }
>     }
> }

It is a pity that the evaluator of that bug didn't clearly state what was
happening: the JDK has always used synchronization on the Thread object
itself to control concurrent access, and this includes the use of wait() in
the implementation of the join() method. Consequently, as a thread
terminates (logically by the code that causes run() to execute) a
notifyAll() is done on the Thread object to wake up any joiners.

Use of the Thread object is a bad idea from an encapsulation perspective and
is not required by the spec. In the tutorials that Doug Lea and I have given
since 1996 we have always warned people away from using Thread objects in
their own synchronization protocols due to their use by the runtime
libraries.

Cheers,
David Holmes



More information about the Concurrency-interest mailing list