• Post Reply Bookmark Topic Watch Topic
  • New Topic

synchronized again  RSS feed

 
Bob Moranski
Ranch Hand
Posts: 177
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, I was wondering if there is a difference between
synchronized void doThis(){
//code
}
and
void doThis(){
synchronize(this){
//code
}
}
 
Todd Bush
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the first sample, the whole method is synchronized. In the second, only the code between
synchronized(this) {
//code
}
would be synchronized.
 
Jerry Pulley
Ranch Hand
Posts: 221
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Bob,
The two code samples you presented have exactly the same effect.
jply
 
Bob Moranski
Ranch Hand
Posts: 177
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you so very much!
 
Suneel Setlur
Ranch Hand
Posts: 202
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The two scenarios do not generate the same op-codes.
The synchronized method generates the monitor-enter and monitor- exit op-code, while the synchronized block does'nt generate these two op-codes. Also it is said that the method synchronization is faster than the block synchronization.
------------------
Suneel
 
Jerry Pulley
Ranch Hand
Posts: 221
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Suneel,
The exact bytecodes may differ, but how many of us are actually concerned with the code at that level? The same behavior can be accomplished with different bytecode arrangements.
Anyway, look at JLS2 8.4.3.6 and 14.18. Sun guarantees that both of the code samples Bob presented will have the same effect.
Regarding performance, there is a small penalty associated with the <code>synchronized</code> statement vice a <code>synchronized</code> method in some circumstances in some VM's. But this penalty is tiny compared to the performance benefit you can gain by making the critical section as small as possible, because that reduces the chance that two threads will contend for the lock, and contention is where you really take a performance hit.
So when I really need to sync the entire method body, and the appropriate monitor is the method's object, I use a sync'ed method. Most of the time, however, a sync'ed statement is more appropriate and performs better.
Jerry
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!