Synchronized threads and locking

Viewed 573

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 the 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 the above examples?

3 Answers
Related