When do I need to use AtomicBoolean in Java?

前端 未结 5 1772
情话喂你
情话喂你 2020-12-02 03:55

How I can use AtomicBoolean and what is that class for?

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-02 04:36

    Excerpt from the package description

    Package java.util.concurrent.atomic description: A small toolkit of classes that support lock-free thread-safe programming on single variables.[...]

    The specifications of these methods enable implementations to employ efficient machine-level atomic instructions that are available on contemporary processors.[...]

    Instances of classes AtomicBoolean, AtomicInteger, AtomicLong, and AtomicReference each provide access and updates to a single variable of the corresponding type.[...]

    The memory effects for accesses and updates of atomics generally follow the rules for volatiles:

    • get has the memory effects of reading a volatile variable.
    • set has the memory effects of writing (assigning) a volatile variable.
    • weakCompareAndSet atomically reads and conditionally writes a variable, is ordered with respect to other memory operations on that variable, but otherwise acts as an ordinary non-volatile memory operation.
    • compareAndSet and all other read-and-update operations such as getAndIncrement have the memory effects of both reading and writing volatile variables.

提交回复
热议问题