Reputation: 1258
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
}
}
}
Upvotes: 0
Views: 70
Reputation: 234635
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.
Upvotes: 1
Reputation: 182
This will synchronize access to the locked class instead of the this/current object. Use whichever you find easier and more effective.
Upvotes: 0
Reputation: 57114
No, this
is an instance of Example
while Example.class
is an instance of Class
.
Upvotes: 1
Reputation: 961
No, this
use current object as monitor, but Example.class
use Example.class
as monitor.
Upvotes: 3