Help coderanch get a
new server
by contributing to the fundraiser
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Regarding synchronization

 
Ranch Hand
Posts: 81
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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).
 
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.


 
Who knew that furniture could be so violent? Put this tiny ad out there to see what happens:
We need your help - Coderanch server fundraiser
https://coderanch.com/t/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic