Wulf Wulf - 1 year ago 71
Java Question

Concurrency: Changing a variable with unsynchronized methods

Take this

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();


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

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download