Tony Stark Tony Stark - 2 months ago 8
Java Question

in the context of the example provided, does dividing method into parts using synchronized(this) helps with performance?

I'm new to java concurrency and I saw an example online of trying to improve performance while maintaining concurrency by synchronise on part of a method.

Example:

public class TwoSums {

private int sum1 = 0;
private int sum2 = 0;

public void add(int val1, int val2){
synchronized(this){
this.sum1 += val1;
this.sum2 += val2;
}
}
}


Improved example:

public class TwoSums {

private int sum1 = 0;
private int sum2 = 0;

public void add(int val1, int val2){
synchronized(this){
this.sum1 += val1;
}
synchronized(this){
this.sum2 += val2;
}
}
}


The author of the article mentioned that:


Now two threads can execute the add() method at the same time. One
thread inside the first synchronized block, and another thread inside
the second synchronized block. This way threads will have to wait less
for each other to execute the add() method.


My question is, for the improved example, even though the method is divided into two parts using
syncrhonised(this)
, we are still synchronising on the SAME "this" object, so even though two different thread can access the method
add
at the same time, we still CAN'T update the value of
sum1
and
sum2
at the same time, right? But the author said we CAN.

I am very confused by it. Any help would be greatly appreciated. Thanks in advance for any help!

Answer

Umm. I don't think the second version will be faster. Because in the second version, the first thread acquires the monitor (this) at line -1 and then even if the second thread arrives, it will have to wait for the first thread to release the lock / monitor, (and cannot proceed).

Additionally, 2 synchornized blocks means additional Memory barrier instructions emitted by the JVM, which means additional flushing of memory. The second one should actually be slower.

Comments