Why java.util.concurrent.atomic.AtomicBoolean is i

2020-06-07 06:27发布

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?

2条回答
神经病院院长
2楼-- · 2020-06-07 07:13

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.

查看更多
贪生不怕死
3楼-- · 2020-06-07 07:27

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.

查看更多
登录 后发表回答