veritas veritas - 10 days ago 5
Java Question

long and double assignments are not atomic - How does it matter?

We know that long and double assignments are not atomic in Java until they are declared volatile. My question is how does it really matter in our programming practice.
for instance if you the see below classes whose objects are being shared among multiple threads.

/**
* The below class is not thread safe. the assignments to int values would be
* atomic but at the same time it not guaranteed that changes would be visible to
* other threads.
**/
public final class SharedInt {

private int value;

public void setValue(int value) {
this.value = value;
}

public int getValue() {
return this.value;
}

}


Now consider another SharedLong

/**
* The below class is not thread safe because here the assignments to long
* are not atomic as well as changes are not
* guaranteed to be visible to other threads.
*/
public final class SharedLong {

private long value;

public void setValue(long value) {
this.value = value;
}

public long getValue() {
return this.values;
}
}


Now we can see the both of the above versions are not thread safe. In case of
int
, it is because threads may see stale values of integer. While in case if
long
, they can see corrupt as well as stale values of long variable.

In both cases, if an instance is not shared among multiple threads, then the classes are safe.

To make the above classes thread safe we need to declare int and long both to be volatile or make the method synchronized.
This make me wonder: How does it really matter if assignments to
long
and
double
are not atomic during our normal course of programming because both need to be declared volatile or synchronized for multithreaded access so my Questions is What are the scenarios where the fact that long assignments are not atomic may make a difference?.

Answer

Where improper programming with an int may result in stale values being observed, improper programming with a long may result in values that never actually existed being observed.

This could theoretically matter for a system that only needs to be eventually-correct and not point-in-time correct, so skipped synchronization for performance. Although skipping a volatile field declaration in the interest of performance seems on casual inspection like foolishness.