Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

util.concurrent.atomic.AtomicBoolean: practical reference

util.concurrent.atomic.AtomicBoolean: practical reference: AtomicBoolean provides atomic boolean reads, writes, compare-and-set, and memory-effect variants.

Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime

Syntax

java.util.concurrent.atomic.AtomicBoolean

AtomicBoolean provides atomic boolean reads, writes, compare-and-set, and memory-effect variants.

Use AtomicBoolean for one independently updated flag that needs atomic compare-and-set or explicitly chosen volatile, acquire, release, opaque, or plain access modes.

AtomicBoolean does not make a multi-field protocol atomic and is not a replacement for Boolean. weakCompareAndSet variants may fail spuriously and access modes have different memory effects.

The no-argument value starts false. compareAndExchange returns the witnessed old value, while compareAndSet returns success; retry loops must tolerate contention and avoid hidden side effects.

The example exercises the documented element in a small deterministic program and compares exact standard output.

Examples

public class Main {
    public static void main(String[] args) throws Exception {
        var value = new java.util.concurrent.atomic.AtomicBoolean(false);
        System.out.println(value.compareAndSet(false, true));
        System.out.println(value.get());
    }
}

Result

true
true

The example exercises the documented element in a small deterministic program and compares exact standard output.

Sources