Java
AtomicBoolean
Programming
Concurrency Control
Multi-threading

When do I need to use AtomicBoolean in Java?

Codemia Knowledge Hub ·

Use AtomicBoolean when multiple threads read and update a boolean and you want thread safety without synchronized blocks or locks. Its main advantage over a plain boolean is atomic conditional updates such as compareAndSet(expectedValue, updateValue), which let you check and change the flag as one indivisible step.

AtomicBoolean lives in java.util.concurrent.atomic, alongside other classes that support atomic operations on single variables. It wraps a boolean and offers simple reads and writes plus atomic conditional updates. Each operation appears to other threads as a single, indivisible action.

Where AtomicBoolean fits

1. Lock-free thread safety for booleans

When a boolean is read and written by several threads and you do not want synchronized blocks, get(), set(boolean newValue) and getAndSet(boolean newValue) take care of memory visibility and ordering.

2. Non-blocking algorithms

For code that must avoid blocking, compareAndSet gives a lock-free check-and-act. A typical case is a method that must initialize a component only once, like singleton initialization.

3. Signaling between threads

A producer thread can set the boolean to true once data is available while a consumer thread checks it periodically.

4. Building larger atomic classes

A custom class that needs atomic operations across several related boolean fields can build on multiple AtomicBoolean instances.

Example: stopping a thread with an AtomicBoolean flag

java
1import java.util.concurrent.atomic.AtomicBoolean;
2
3public class StoppableTask extends Thread {
4    private AtomicBoolean running = new AtomicBoolean(true);
5
6    public void stopTask() {
7        running.set(false);
8    }
9
10    public void run() {
11        while (running.get()) {
12            // task code
13        }
14    }
15}
16
17// Usage
18StoppableTask task = new StoppableTask();
19task.start();
20// When needed to stop
21task.stopTask();

The thread keeps checking the AtomicBoolean to decide whether to continue, and stopTask() calls set(false) to change that state safely across threads.

Why choose AtomicBoolean over locks

  • Thread safety without locks: managing a boolean this way is simpler than using locks and sometimes more efficient.
  • Memory efficiency: it manages a single boolean, so it is lighter than locking mechanisms or atomic classes for larger data types.
  • Ease of use: the API is small and built for boolean operations.
FeatureDescription
Thread SafetyEnsures that updates and reads of a boolean are visible across threads without explicit synchronization.
Lock-Free EfficiencyCan perform better than lock-based synchronization in some scenarios, particularly in low-contention environments.
Atomic OperationsProvides methods like compareAndSet, getAndSet which are essential for non-blocking algorithms.
Use CasesIdeal for flag setting, state signaling, and building non-blocking structures.

Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Interview Questions practice on Codemia

Over 11,000 interview practice questions for 300+ companies, searchable by company and role.

Browse interview questions