File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Threads and Synchronization and the fly likes Accessing Synchronized methods in a single object Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Accessing Synchronized methods in a single object" Watch "Accessing Synchronized methods in a single object" New topic
Author

Accessing Synchronized methods in a single object

Gaurav Gupta
Greenhorn

Joined: Jan 15, 2004
Posts: 13
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

Joined: Jul 08, 2003
Posts: 24187
    
  34

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.


[Jess in Action][AskingGoodQuestions]
Gaurav Gupta
Greenhorn

Joined: Jan 15, 2004
Posts: 13
thanks Ernest
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Accessing Synchronized methods in a single object