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.

Example

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)) {
          System.out.println("initializing");
      }
  }
 
  public static void main(String[] args) throws InterruptedException {
      int c = 5;
      ExecutorService executorService = Executors.newFixedThreadPool(c);
      for (int i = 0; i < c; i++) {
    	  executorService.execute(AtomicBooleanTest::init);
      }
      executorService.shutdown();
      executorService.awaitTermination(10, TimeUnit.MINUTES);
  }
}

Output

initializing
Content Protection by DMCA.com
Please Share