• 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Knute Snortum
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Ganesh Patekar
  • Stephan van Hulst
  • Pete Letkeman
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Ron McLeod
  • Vijitha Kumara

Regarding Synchronized  RSS feed

 
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I know that if we use criteria section like below:
synchronized(Object o) {
//some code...
}
the section will obtain the lock of object o;
But the confusing thing for me is that which lock will be obtained by the section when defining a method with "synchronized", like below:
synchronized void aMethod() {
//some code...
}
then aMethod() obtain whose lock??
Thank you!
 
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think it uses the lock of the object you're calling the method on.
So, if you have

when you call aMethod(), it's using the lock on object foo, IIRC. I won't swear to it, but I'm pretty sure that's right, because another thread can't enter any other synchronized method on object foo, while a thread is running inside synchronized method aMethod().
 
Ranch Hand
Posts: 697
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Richard, Phil is exactly correct.
If the method is sychronized, and if you call the method from other class, then the lock on the object where the method is present, is obtained by the calling class.
So from the example of Phil, class Driver obtians lock on the object foo which is SomeClass instance.
Hope this clarifies. Thanks.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!