5969bruce 5969bruce - 4 months ago 17
Java Question

In java, when variables such as Long, long, Double ,double are autoboxing or unboxing, is reading or writing operation atomic?

I know this:


Reads and writes are atomic for reference variables and for most primitive variables (all types except long and double).
Reads and writes are atomic for all variables declared volatile (including long and double variables).


But I want to know
When variables such as Long, long, Double ,double are autoboxing or unboxing, is reading or writing operation atomic?

For example:

private Long a;
private long b;
private Double c;
private double d;

a = 2; //is this operation atomic?
b = a; //is this operation atomic?
d = 3;
c = d; //is this operation atomic

Answer

You said:

Reads and writes are atomic for reference variables and for most primitive variables (all types except long and double)

a = 2;

This is a write to a reference variable, so it's atomic

b = a;

This is equivalent to

read a
call a.longValue()
assign result to b

So this reads a reference variable (atomic), then gets an immutable long value from the Long object (so atomicity is irrelevant) and writes to a long primitive (so no guarantee to be atomic)

d = 3;

This writes to a primitive double (so no guarantee to be atomic)

c = d;

This is equivalent to

read d
call Double.valueOf(value)
assign result to b

So this reads from a primitive double (so no guarantee to be atomic), then transforms the value to a Double and writes that reference to a reference variable (atomic)