2 Replies Latest reply on Jul 24, 2011 2:48 PM by Kayaman

    Synchronized methods and thread locking

      Hi can someone please explain the difference between these two examples in the context of object locking
      public void method1(){
      StringBuffer aStringBufferObject = new StringBuffer("A");
      public void method2(){
      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.


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