Thursday, 11 May 2017

multithreading - Strange java behavior of wait/notify

It's because you're waiting on a Thread instance. Thread uses wait/notify/notifyAll internally, so you shouldn't do that yourself as well - you'll confuse Thread, and Thread will confuse you. In particular, when a thread exits, it calls this.notifyAll().




From the documentation of Thread.join:




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.




In general, try to lock and wait for objects which nothing else can interact with. That way you can reason about the concurrency-related operations which exist on the object, because they're very limited. As soon as arbitrary code can synchronize on the object (and call wait/notify etc) it's hard to prove that your code is correct. That's why you'll often see something like:



public class Foo {

private final Object lock = new Object();

... code which uses synchronized(lock) ...
}

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...