• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

synchronized method(s) purpose

 
Harikrishna Gorrepati
Ranch Hand
Posts: 423
  • Mark post as helpful
  • send pies
  • 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.


 
Ralph Cook
Ranch Hand
Posts: 479
  • Mark post as helpful
  • send pies
  • 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
  • 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 ?
 
Matthew Brown
Bartender
Posts: 4566
8
  • Mark post as helpful
  • send pies
  • 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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic