Forum Stats

  • 3,837,134 Users
  • 2,262,229 Discussions
  • 7,900,211 Comments

Discussions

Synchronized methods and thread locking

ziggy25
ziggy25 Member Posts: 215
Hi can someone please explain the difference between these two examples in the context of object locking
public void method1(){
    synchronized(this){
        ....
    }
}
And
StringBuffer aStringBufferObject = new StringBuffer("A");

public void method2(){
    synchronized(aStringBufferObject){
        ....
    }
}
I know the first example will obtain a lock on the this instance and the second will obtain a lock of the aStringBufferObject instance. But i dont really understand what the effect or the difference of teh two is.

For example, in the second example, will threads still be able to execute the code inside the synchronized block because the lock is not related to the 'this' instance?

I know that synchronizing a method or a block of code prevents multiple threads to access that block/method at the same time but what is the purpose of specifying the object to lock on and what is the difference in the way the object is specified as in teh above examples.

Thanks

Edited by: ziggy on Jul 24, 2011 3:23 PM
Tagged:

Answers

This discussion has been closed.