Wulf Wulf - 11 days ago 7
Java Question

Concurrency: Changing a variable with unsynchronized methods

Take this

ConcurrentDouble
class definition as an example:

public class ConcurrentDouble {

public double num = 0;

public void subtract(double num) {
this.num -= num;
}

public void add(double num) {
this.num += num;
}
}


Now if I did the following,

public class Test {
public static void main(String[] args) {
ConcurrentDouble d1 = new ConcurrentDouble();

Thread one = new Thread(() -> { d1.add(5); }).start();
Thread two = new Thread(() -> { d1.subtract(5); }).start();

one.join();
two.join();

System.out.println(d1.num); // <-- OUTPUT
}
}


We know the number starts off at
0
, and we expect it to have
0
at the end. Is it possible that the number becomes
-5.0
or
5.0
?

Answer

Yes, it's possible. -= and += are not atomic operations. And even then, the JVM doesn't guarantee that a write to a double is atomic.