• 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:

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: 80613
467
  • 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?
 
Sheriff
Posts: 28394
100
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.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic