Easy learning with example program codes

atomicboolean in java

The java.util.concurrent.atomic.AtomicBoolean class provides a boolean variable which can be read and written atomically.

Creating an AtomicInteger

AtomicBoolean atomicBoolean = new AtomicBoolean();

Create an atomic boolean with the default value false.

AtomicBoolean atomicBoolean = new AtomicBoolean(true);

Create an atomic boolean with the initial value true.

Commonly used methods of AtomicBoolean class

  • get(): Reads the value atomically.
  • set(boolean newValue): Writes the value atomically.
  • compareAndSet(boolean expect, boolean update): Variable value is compared to the expect param, and if they are equal, then the value is set to the update param and true is returned.
  • getAndSet(boolean newValue):It returns the current value and sets the new value.


import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
public class AtomicBooleanTest {
  private static AtomicBoolean init = new AtomicBoolean();
  public static void init() {
      if (init.compareAndSet(false, true)) {
  public static void main(String[] args) throws InterruptedException {
      int c = 5;
      ExecutorService executorService = Executors.newFixedThreadPool(c);
      for (int i = 0; i < c; i++) {
      executorService.awaitTermination(10, TimeUnit.MINUTES);



Related topics

Please follow and like us:
Posted in Java   

Core Java Tutorial

Copyright © 2019 CodesJava Protection Status SiteMap Reference: Java Wiki