Why java.util.concurrent.atomic.AtomicBoolean is internally implemented with int?

此生再无相见时 提交于 2020-01-01 03:58:08

问题


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?


回答1:


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.




回答2:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!