This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

sychronized block in synchronized method

 
Li Yang
Greenhorn
Posts: 7
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1070
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 7
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 167
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic