I Don`t understand the following behaviour: i habe an object referenced by variable a, im synchronizing 2 methods on it first method calls wait on it. second method creates a new object and assigns it to varable a, than synchronizes on a (the new Object!!!) But when calling notifyAll() a waiting thread (who called meth1)is waked up. But is`nt it true, that we are dealing here with 2 different objects due to the new object instantiation?
in the second thread executes actually BEFORE the line
in the first thread. So the newly created thread actually synchronizes on the second object, to which the static field "a" is referring.
This could happen because the actual behaviour of the thread scheduler is unknown, it could start the doIt2() method in the main thread before the doIt() method in the created thread.
Joined: Dec 16, 2007
I've just checked, this is really the case. If you call a Thread.sleep(500) before changing the a field in the doit2 method, you will give the created thread a chance to synchronize on the first object before loosing it, and everything will go on as you expected.
As for the code
It really throws an exception, because you're trying to call notifyAll on a newly created object that you didn't lock.