What is the difference between the two synchronizations:
public synchronized void set (int i) {
this.i = i;
}
and
public void set (int i) {
synchronized (this) {
this.i = i;
}
}
What is the difference between the two synchronizations:
public synchronized void set (int i) {
this.i = i;
}
and
public void set (int i) {
synchronized (this) {
this.i = i;
}
}
First one is synchronized method and second one is synchronized block.
Here as you synchronized
on this object in block both represent same. In synchronized-method
thread acquire the lock of current object.
Note: in synchronized block you can synchronize block of code instead whole method body, as well use different resource for locking(except this).
synchronized(this)
is writtenSo if you write second method as
public void set (int i) {
// Code here is not synchronized
synchronized (this) { // only this block of code is synchronized
this.i = i;
}
// code after this is also not synchronized.
}
But in case of second block, you can also synchronize of some other object.
public void set (int i) {
synchronized (someObject) {
this.i = i;
}
}
They are different ways of writing the same thing. Java could have just had the second form. Synchronizing the whole body of a method on the method's this
object is a particularly common case, so the language provides a quick, simple way of doing it.
The Java Language Specification states the equivalence in 8.4.3.6 synchronized Methods. synchronized void bump() { count++; }
has exactly the same effect as
void bump() {
synchronized (this) {
count++;
}
}
These two synchronisation methods are equivalent because you gave this
in the synchronized block
.
The synchronization is based on the Intrinsic Lock or Monitor Lock, an attribute of each Object
As the other answers stated your first proposition is a synchronized method
which means that the thread will acquire the lock of the current Object.
From the Oracle Tutorials :
When a thread invokes a
synchronized method
, it automatically acquires the intrinsic lock for that method's object and releases it when the method returns. The lock release occurs even if the return was caused by an uncaught exception.
Your second proposition is a synchronized block
or synchronized statement
. In this case the thread acquire the lock of the object put in argument.
Again from the Oracle Tutorials :
Unlike synchronized methods, synchronized statements must specify the object that provides the intrinsic lock:
In your case you put this
so it will take the lock of the current object as the synchronized method did.
But you can also give it another object and it will take its lock leaving the current object lock "unchanged"
There is no difference between the two synchronizations, but the second one is more flexible: you can add unsynchronized code outside the synchronized
block in the same method, or synchronize on an object different from this
.