Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Regarding synchronization

 
Tusshar Fasate
Ranch Hand
Posts: 81
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.


 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic