Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Question of synchronized(aObject)  RSS feed

 
Michael Deng
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is the difference between:
public void aMethod(){
synchronized(aObject){
//code
aObject.wait();
//code
}
}
and
public synchronized void aMethod(){
//code
aObject.wait();
//code
}

Thanks for your help!
Michael
 
David Harrigan
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nothing really. The only difference is the first code example offers more granularity when it comes to threading and scheduling. Since the JVM doesn't have to lock the entire method then another thread could access parts of that method (a case in mind is if you have a if..then condition, the true part could be synchronized as it updates a bit of data common to both threads for example. There's no need to acutally lock down the entire method.
The first method, to quote the Java Programming Language 3rd Edition is "syntactic shorthand" for what is in effect the same as the second code example.
Anyone else like to further develop this answer?
 
Jim Baiter
Ranch Hand
Posts: 532
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also, I believe that the monitor obtained will be that
of "anObject" rather than this current class (this) in
which the synchronized method resides.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!