• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
  • Paul Clapham
  • Liutauras Vilda
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

synchronizing doubt

 
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks a lot.
I was to blind to see this
 
permaculture is largely about replacing oil with people. And one tiny ad:
We need your help - Coderanch server fundraiser
https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic