Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Regarding Synchronized

 
Richard Yi
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!
 
Phil Rhodes
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().
 
Satish Avadhanam
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic