Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • 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:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Bear Bibeault
  • Knute Snortum
  • Liutauras Vilda
Sheriffs:
  • Tim Cooke
  • Devaka Cooray
  • Paul Clapham
Saloon Keepers:
  • Tim Moores
  • Frits Walraven
  • Ron McLeod
  • Ganesh Patekar
  • salvin francis
Bartenders:
  • Tim Holloway
  • Carey Brown
  • Stephan van Hulst

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.
 
Let me tell you a story about a man named Jed. He made this tiny ad:
RavenDB is an Open Source NoSQL Database that’s fully transactional (ACID) across your database
https://coderanch.com/t/704633/RavenDB-Open-Source-NoSQL-Database
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!