How to differentiate when wait(long timeout) exit for notify or timeout?

There is one more reason that notify can return: spurious wakeup. This is an unlikely but possible thing, because preventing spurious wakeups is very expensive on some hardware/OS combinations. Because of this you always have to call wait() in a loop and re-check the condition that you are waiting for. During this work it’s easy … Read more

Why does notifyAll() raise IllegalMonitorStateException when synchronized on Integer?

You have noted correctly that notifyAll must be called from a synchronized block. However, in your case, because of auto-boxing, the object you synchronized on is not the same instance that you invoked notifyAll on. In fact, the new, incremented foo instance is still confined to the stack, and no other threads could possibly be … Read more

How can the wait() and notify() methods be called on Objects that are not threads?

Locking is about protecting shared data. The lock is on the data structure being protected. The threads are the things accessing the data structure. The locks are on the data structure object in order to keep the threads from accessing the data structure in an unsafe way. Any object can be used as an intrinsic … Read more

Java executors: how to be notified, without blocking, when a task completes?

Define a callback interface to receive whatever parameters you want to pass along in the completion notification. Then invoke it at the end of the task. You could even write a general wrapper for Runnable tasks, and submit these to ExecutorService. Or, see below for a mechanism built into Java 8. class CallbackTask implements Runnable … Read more