• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Synchroniztion

 
Naveen Kota
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is the difference between a synchronized method and using a synchronized block. What difference does it make logically and which is more efficient
 
Tom Billings
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A synchronzed method always locks on this object (unless it's a static method in which case the lock is held on a class-level).

A synchronized block locks on any object, however, locking the this object with a synchronized block is similar to using a synchronized method. But, it may be more efficient to use a synchonized block if the lock isn't nesseccary throughout the whole method.

Hence, if you use the this object:

public void synchronized foo() {

}

is similar to:

public void foo() {
synchronized(this) {

}
}
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic