Skip to main content

Command Palette

Search for a command to run...

Java AtomicBoolean

Published
2 min readView as Markdown
Java AtomicBoolean

Introduction

AtomicBoolean, as part of the java.util.concurrent.atomic package, provides a boolean value that can be updated atomically. This means that operations on an AtomicBoolean, such as setting, getting, and comparing the value, are guaranteed to be performed as a single, indivisible operation, ensuring thread-safety in concurrent environments.

Key characteristics:

  • Thread-Safety:

    AtomicBoolean addresses the issue of race conditions that can occur when multiple threads access and modify a shared boolean variable simultaneously. It ensures that updates are atomic, preventing data corruption and inconsistent states.

  • Atomic Operations:

    It provides methods for performing atomic operations, including:

    • get(): Returns the current value.
    • set(boolean newValue): Atomically sets the value to newValue.
    • compareAndSet(boolean expectedValue, boolean newValue): Atomically sets the value to newValue if the current value equals expectedValue. This is a crucial method for implementing non-blocking algorithms.
    • getAndSet(boolean newValue): Atomically sets the value to newValue and returns the previous value.

Usage

  • Use Cases:

    AtomicBoolean is commonly used for implementing flags or indicators in multithreaded applications, such as:

    • Controlling access to a shared resource.
    • Signaling completion of a task.
    • Implementing locks or synchronization mechanisms.

Example:

import java.util.concurrent.atomic.AtomicBoolean;

public class AtomicBooleanExample {
    private static AtomicBoolean flag = new AtomicBoolean(false);

    public static void main(String[] args) {
        // Thread 1
        new Thread(() -> {
            if (flag.compareAndSet(false, true)) {
                System.out.println("Thread 1 acquired the flag.");
                // Perform some operation
            } else {
                System.out.println("Thread 1 failed to acquire the flag.");
            }
        }).start();

        // Thread 2
        new Thread(() -> {
            if (flag.compareAndSet(false, true)) {
                System.out.println("Thread 2 acquired the flag.");
                // Perform some operation
            } else {
                System.out.println("Thread 2 failed to acquire the flag.");
            }
        }).start();
    }
}

Conclusion

In conclusion, AtomicBoolean is an essential tool in Java's concurrent programming toolkit, enabling developers to build high-performance, thread-safe, and reliable multithreaded applications by providing a simple and efficient way to manage shared boolean states.