-2

How Java synchronization behaves if a method parameter is used in the synchronization block instead of this keyword.

public void doSomething(final MyInterface iface) {
  synchronized(this) {
    // ... do some work
  }
}

vs

public void doSomething(final MyInterface iface) {
  synchronized(iface) {
    // ... do some work
  }
}

Will the net effect be the same?

Niranjan
  • 2,601
  • 8
  • 43
  • 54

2 Answers2

2

The two cases are completely different.

When you use synchronized, a lock (monitor) is obtained on the object that is passed as argument.

synchronized(this) --> Thread obtains lock on "current" object.

synchronized(iface) --> Thread obtains lock on "iface" object

Will the net effect be the same?

No, the effects could be devastatingly different.

TheLostMind
  • 35,966
  • 12
  • 68
  • 104
1

Have you ever read JLS? Synchronization on this keyword implies synchronization on object itself (on which method was invoked). It is clear that this object and object referenced by parameter aren't same things in general.

Andremoniy
  • 34,031
  • 20
  • 135
  • 241