File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Regarding synchronization Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Regarding synchronization" Watch "Regarding synchronization" New topic

Regarding synchronization

Tusshar Fasate
Ranch Hand

Joined: May 21, 2008
Posts: 81
Suppose,I hava 10 methods in my class say method1(),method2(),.....method10()..

And I am calling method10() in method9(),method9() in method8()..till method1()...

If I marked method1() as synchronized Is there any need to mark other 9 methods as synchornized?

Please reply to this my confusion.
Amit Vinod Dali
Ranch Hand

Joined: Apr 14, 2010
Posts: 42
When a thread invokes a synchronized method, it automatically acquires the lock for that method's object and releases it when the method returns. The lock release occurs even if the return was caused by an uncaught exception.
So there is not need mark other 9 methods as synchornized(unless it is required).
Doug Braidwood
Ranch Hand

Joined: Apr 04, 2010
Posts: 42
You can call non-synchronized methods from synchronized ones but you should probably think carefully before doing so.

Whilst you are in one of the synchronized methods of an object, any methods which are not synchronized can still be accessed by other threads.

For example this code will return Two times 2 is 6 even though the method doubler is synchronized.
However if you also make setX synchronized it will work correctly.

I agree. Here's the link:
subject: Regarding synchronization
It's not a secret anymore!