• 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

synchronized method(s) purpose

 
Ranch Hand
Posts: 423
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Are there any differences in the following 3 programs in terms of locking on 1 or 2 methods or within the method.


 
Ranch Hand
Posts: 479
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Can you perhaps make your question more clear? I can't tell what you're asking.

rc
 
Harikrishna Gorrepati
Ranch Hand
Posts: 423
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Sure. Let me start step by step. If I say a single method is synchronized, Do we get lock on that particular method or whole class level ?
 
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If you mark a static method synchronized, it synchronizes on the class. A thread entering one of these prevents another thread entering any other such method.

If you mark a normal method synchronized, it synchronizes on the instance. So two threads can run the method at the same time if they're called on different objects, but on the same object only one synchronized method can be called at a time.

Your method3 example is a long-hand way of doing exactly the same as marking the method synchronized. This gives you more flexibility because:
a) You can synchronize on any object you want
b) You can synchronize only part of the method body, if you want
If you don't need this flexibility, just use the short-cut of marking the method.
reply
    Bookmark Topic Watch Topic
  • New Topic