• 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
  • Tim Cooke
  • Devaka Cooray
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Carey Brown
  • Tim Holloway
Bartenders:
  • Martijn Verburg
  • Frits Walraven
  • Himai Minh

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.
 
Think of how dumb the average person is. Mathematically, half of them are EVEN DUMBER. Smart tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic