• 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
  • Ron McLeod
  • Paul Clapham
  • Tim Cooke
  • Devaka Cooray
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
Bartenders:
  • Carey Brown
  • Roland Mueller

Locks and synchronization

 
Ranch Hand
Posts: 212
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
We know that locks are associated with objects. In the below example program there are 3 synchronized methods. Lock is acquired for which object? Also when a thread is executing the increment method can a second thread invoke the decrement method?

 
Marshal
Posts: 79699
381
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

raja singh kumar wrote:. . . . Lock is acquired for which object?

Look in the Java® Language Specification. It tells you which object is used as the monitor.
If I remember correctly, a synchronised method is equivalent to wrapping the whole content of the method in synchronized (this) { ... }

Also when a thread is executing the increment method can a second thread invoke the decrement method? . . .

That is the whole point of the synchronisation: stop a second thread accessing decrement() until increment() has completed and the lock has been released. I presume the get method was only there to show how the examplle works. Please work out whether you really need that get method to be synchronised.
 
raja singh kumar
Ranch Hand
Posts: 212
1
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I dont get it. Is the lock acquired on object of SynchronizedCounter when accessing synchronized method of  SynchronizedCounter?
 
Marshal
Posts: 28295
95
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes, that's it exactly. The "synchronized" keyword, when it doesn't specify an object to synchronize on, synchronizes on "this". Which in your example means the SynchronizedCounter which is about to execute the synchronized method.
 
keep an eye out for scorpions and black widows. But the tiny ads are safe.
We need your help - Coderanch server fundraiser
https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic