aspose file tools*
The moose likes Threads and Synchronization and the fly likes sychronized block in synchronized method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "sychronized block in synchronized method" Watch "sychronized block in synchronized method" New topic
Author

sychronized block in synchronized method

Li Yang
Greenhorn

Joined: Sep 28, 2000
Posts: 7
I'm puzzled by the following method seen in my work:
public synchronized void syncMethod() {
// blah
synchronized (this) {
// blah
}
}
Note that the two 'synchronized' key words make you think that the calling thread will lock the same object. Surprisingly, the method does not cause deadlock. Here are the questions:
1) Why that method does not cause deadlock?
2) Does this kind of method, i.e., the double sync, cause any inefficiency?
Thanks.
bill bozeman
Ranch Hand

Joined: Jun 30, 2000
Posts: 1070
This method is putting 2 locks on the same object which to me seem like a waste, but it is perfectly legal. Code will work and it won't deadlock it because it you are just putting another lock on something with which you already have a lock on. Deadlock would be caused by locking one object, but in your run method you need access to another object which also is locked. So it is two or more locked objects trying to access each other.
hope this helps
Bill
Li Yang
Greenhorn

Joined: Sep 28, 2000
Posts: 7
Thanks, Bill. I found the following in JLS (14.18) to share with everyone:
A single thread may hold a lock more than once.
The example:
class Test {
public static void main(String[] args) {
Test t = new Test();
synchronized(t) {
synchronized(t) {
System.out.println("made it!");
}
}
}
}
prints:
made it!
This example would deadlock if a single thread were not permitted to lock a lock more than once.
Originally posted by bill bozeman:
This method is putting 2 locks on the same object which to me seem like a waste, but it is perfectly legal. Code will work and it won't deadlock it because it you are just putting another lock on something with which you already have a lock on. Deadlock would be caused by locking one object, but in your run method you need access to another object which also is locked. So it is two or more locked objects trying to access each other.
hope this helps
Bill

ricky gonzalez
Ranch Hand

Joined: Jun 30, 2000
Posts: 167
Hi, I just came across this. It is called lock re-entrance, and it is perfectly legal.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: sychronized block in synchronized method