I wrote a test app that should never stop. It issues t.wait()
(t
is a Thread
object), but I never call notify. Why does this code end?
You're waiting on a Thread
- and while most objects aren't implicitly notified, a Thread
object is notified when the thread terminates. It's documented somewhere (I'm looking for it...) that you should not use wait
/notify
on Thread
objects, as that's done internally.
This is a good example of why it's best practice to use a "private" object for synchronization (and wait/notify) - something which only your code knows about. I usually use something like:
private final Object lock = new Object();
(In general, however, it's cleaner to use some of the higher-level abstractions provided by java.util.concurrent if you can. As noted in comments, it's also a good idea to implement Runnable
rather than extending Thread
yourself.)
The JavaDoc for wait
gives the answer: spurious wakeups are possible. This means the JVM is free to end a call to wait
whenever it wants.
The documentation even gives you a solution if you don't want this (which is probably always the case): put the call to wait
in a loop and check whether the condition you wait for has become true after every wakeup.