aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Regarding Synchronized Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Regarding Synchronized" Watch "Regarding Synchronized" New topic
Author

Regarding Synchronized

Richard Yi
Greenhorn

Joined: Feb 04, 2004
Posts: 16
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

Joined: Dec 27, 2003
Posts: 65
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().


A+, Network+, SCJP, SCWCD<br />preparing for SCBCD, SCEA, CompTIA I-Net+
Satish Avadhanam
Ranch Hand

Joined: Aug 12, 2003
Posts: 697
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Regarding Synchronized