0

Is the this and Example.this the same object?

E.g. Is the call this and Example.class inside the synchronized the same object?

class Example {
    public Example() {
        synchronized(this) {
            // some code
        }
    }
}


class Example {
    public Example() {
        synchronized(Example.class) {
            // some code
        }
    }
}
luk2302
  • 55,258
  • 23
  • 97
  • 137
felipe
  • 1,212
  • 1
  • 15
  • 27
  • Obivously not. The first is an object, the second the whole class. – Tom Jul 28 '17 at 12:13
  • `Example.class` is the example class. `this` is an specific instance of `Example`. Not the same. – khelwood Jul 28 '17 at 12:13
  • no they are not the same. `this` returns the current instance, whereas `Example.class` returns the instance of the class of `Example` – Lino Jul 28 '17 at 12:14
  • https://stackoverflow.com/questions/26946728/why-do-we-write-synchronizedclassname-class – Filosssof Jul 28 '17 at 12:15

4 Answers4

3

No, this use current object as monitor, but Example.class use Example.class as monitor.

Vadim Beskrovnov
  • 941
  • 6
  • 18
1

No, this is an instance of Example while Example.class is an instance of Class.

luk2302
  • 55,258
  • 23
  • 97
  • 137
1

No.

Synchronizing on this is instance-level locking, meaning that the critical section cannot be re-entered with same object.

Synchronizing on Example.class is class-level locking, meaning that no other instance of the class, including this, can enter that critical section.

As you can see, class-level locking is, in a sense, more drastic.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
0

This will synchronize access to the locked class instead of the this/current object. Use whichever you find easier and more effective.

Sam
  • 182
  • 1
  • 6