Is a notify signalled on thread finish? Why does this code sample work? Is a notify signalled on thread finish? Why does this code sample work? multithreading multithreading

Is a notify signalled on thread finish? Why does this code sample work?


In the Javadoc for Java 7 Thread.join(long)

This implementation uses a loop of this.wait calls conditioned on this.isAlive. As a thread terminates the this.notifyAll method is invoked. It is recommended that applications not use wait, notify, or notifyAll on Thread instances.

Using a Thread directly this way is considered bad practical. Note: wait() could end for any number of reasons, possibly spuriously.


Based on a puzzler related to @Voo's comment. The point is you shouldn't play with the internal behaviour of Thread as this is more likely to lead to confusion.

public static String getName() {    return "MyProgram";}public static void main(String... args) {    new Thread() {       public void run() {           System.out.println("My program is " + getName());        }    }.start();}

What does this program print?


For clarification, I have modified your code to this:

Job thread = new Job();thread.start();final Object lock = new Object();synchronized (lock) { lock.wait(); }System.out.println(thread.getNumber());

Now it blocks. That's a first-hand confirmation of what @Nitram has explained in his answer. If you care to have a look at the Thread implementation code, it will be quite obvious why this is the observed behavior.


NOTE: This answer has been edited extensively.


The reason for this behaviour is, that "someone" is calling notifyAll internally. This "someone" is the JVM itself as you can "see" in the C sources here:

http://hg.openjdk.java.net/jdk7/hotspot/hotspot/file/f95d63e2154a/src/share/vm/runtime/thread.cpp

In line 1531 the method ensure_join calls notifyAll. This is the counterpart to the wait calls in java.lang.Thread#join (as noted by Marko and others).

ensure_join in turn is called in line 1664 in the method JavaThread::exit.


Since this is "internal bookkeeping" nobody should rely on this behaviour.