Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Accessing Synchronized methods in a single object

 
Gaurav Gupta
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
What happens in the following case and why? How would monitor locking of the object work?
There are two synchronized methods in a single object. Two thread try to talk it, one accessing method 1 and other accessing method 2. Can they access these methods simultaneously?
What would be the difference if I make one of these two methods as static?
thanks,
Gaurav
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Gaurav Gupta:

There are two synchronized methods in a single object. Two thread try to talk it, one accessing method 1 and other accessing method 2. Can they access these methods simultaneously?

No, that's the whole point of synchronization. Every synchronized method is associated with a lock. For member methods, the object itself is the lock. Two separate threads can't own the same lock at the same time, so only one of the two threads could proceed. The other couldn't enter the method it called until the first was through with its method.


What would be the difference if I make one of these two methods as static?

Static methods use the Class object as a lock, so the two threads would be using different locks, so they could both proceed.
 
Gaurav Gupta
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks Ernest
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic