wood burning stoves 2.0*
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

Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
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.

subject: Regarding synchronization
Similar Threads
Lock - Object or Method
Static methods can't be overridden?
is static methods can't override?
Passing Object vs Explicit DOT.calls
clarification on why the modifier private changes output..