简体   繁体   中英

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM