1
Public Class A
{
  private Object memberlockObject = new Object();

  public doStuffapproach1(){

      synchronized(this){
               // Do something;
      }
  }

 public doStuffapproach2(){

      synchronized(memberlockObject){
               // Do something;
      }
 }

 public doStuffapproach3(Object parameterLockObject){

      synchronized(parameterLockObject){
               // Do something;
      }
 }

}

In the above code, do the methods doStuffapproach1, doStuffapproach2, doStuffapproach3 achieve the same type of block synchronization or not. If not, how do they differ from each other. In what scenarios should each be used ?

P.S : I understand that method level synchronization is as good as synchronizing whole method body on (this).

Chetan Gowda
  • 390
  • 6
  • 15
  • 1
    Hint: actually you are supposed to do some prior research before asking questions. And well, this stuff is really documented all over the place ... and also try to reduce the number of tags you are using to the essential minimum. – GhostCat Jun 14 '16 at 07:16

1 Answers1

2

When you use the synchronized keyword, you need to define an object to use as a monitor.

synchronized(this) use the current object as monitor

synchronized(otherObject) use another object as monitor

If you need to synchronize on the same object in different classes at least one of them needs to synchronize on something different from this.

Note that define a method as synchronized implicitly will synchronize on this (if the method is not static).


The doStuffapproach1 method synchronize on this so any call to that method on the same object is synchronized.

The doStuffapproach2 works exactly as doStuffapproach1 because you lock on an object that has a unique instance in the current object.

The doStuffapproach3 works differently because you pass the monitor and depends on what you pass as parameter.

Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56