AtomicBoolean stores its value in:
private volatile int value;
Then, for example, extracting its value is done like this:
public final boolean get() {
return value != 0;
}
What is the reason behind it? Why boolean
was not used?
AFAIK, int
is the smallest type CAS operations can be implemented across different machine types.
Note: as object allocations are 8 byte aligned, using a smaller type wouldn't save any memory.
This probably is to be able to base several of the Atomic
classes on the same base (Unsafe
), which uses integer and provides the compare and swap operation.
Concurrency in Practice provides a good explanation of the inner workings.
来源:https://stackoverflow.com/questions/13724858/why-java-util-concurrent-atomic-atomicboolean-is-internally-implemented-with-int