File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes need clarification on the way synchronization works? 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 "need clarification on the way synchronization works?" Watch "need clarification on the way synchronization works?" New topic

need clarification on the way synchronization works?

gurpeet singh
Ranch Hand

Joined: Apr 04, 2012
Posts: 924

following is paragraph from kb 6 book page no. 735.

With locks. Every object in Java has a built-in lock
that only comes into play when the object has synchronized method code. When
we enter a synchronized non-static method, we automatically acquire the lock
associated with the current instance of the class whose code we're executing (the
this instance).

does this means that if an object does not have synchronized methods, we can't acquire lock on that object. if we can acquire the lock , then how we do that ?

according to me the answer is yes, we can acquire lock on any object in java whether it has synchronized methods or not. we can do so using synchronized blocks. please somebody confirm if this is right ???

Mike Smyth

Joined: Apr 11, 2012
Posts: 9
I think your correct, you can think of the synchronized keyword on a method as simply being like having a synchronised block on the particular object say using "this" surrounding the entire method. I suspect that the book is getting at the fact that you don't need to synchronize on any object if you use the synchronized keyword for a method and by doing this it uses the "built-in lock".

Hope this helps,
Helen Ma
Ranch Hand

Joined: Nov 01, 2011
Posts: 451
Yes. I think you can lock on any object by using synchronized(obj) {...} , does not matter the object has syn method or not.
I agree. Here's the link:
subject: need clarification on the way synchronization works?
It's not a secret anymore!