• 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:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

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.


 
reply
    Bookmark Topic Watch Topic
  • New Topic