File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes synchronizing doubt Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "synchronizing doubt" Watch "synchronizing doubt" New topic

synchronizing doubt

Peter Ricke

Joined: Dec 07, 2007
Posts: 24
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?

By the way:
the following code throws an IllegalMonitorStateException:


========<br />class a{<br /> a a(a a){return (a)a;}<br />}
Sergey Petunin
Ranch Hand

Joined: Dec 16, 2007
Posts: 44
I think the problem here is that the line

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.
Sergey Petunin
Ranch Hand

Joined: Dec 16, 2007
Posts: 44
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.
Peter Ricke

Joined: Dec 07, 2007
Posts: 24
Thanks a lot.
I was to blind to see this
I agree. Here's the link:
subject: synchronizing doubt
Similar Threads
wait() method question
wait() releases all locks?
Thread doubt
Question on lock
Calling wait()/ notify() in run()