• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

synchronizing doubt

 
Peter Ricke
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:


Thanks
 
Sergey Petunin
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot.
I was to blind to see this
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic