atomicinteger in java

The java.util.concurrent.atomic.AtomicInteger class provides an int variable which can be read and written atomically.

Creating an AtomicInteger

AtomicInteger atomicInteger = new AtomicInteger();

Create an atomic integer with the default value 0.

AtomicInteger atomicInteger = new AtomicInteger(453);

Create an atomic integer with the initial value 453.

Commonly used methods of AtomicInteger class

  • get(): Reads the value atomically.
  • set(int newValue): Writes the value atomically.
  • compareAndSet(int expect, int 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.
  • addAndGet(int delta): The delta is added to the value and the new value is returned.
  • getAndAdd(int delta): It adds the delta to the value, and returns the previous value.
  • getAndIncrement(): The value is incremented, and its previous value is returned.
  • incrementAndGet(): The value is incremented and its new value is returned.
  • decrementAndGet(): The value is decremented and its new value is returned.
  • getAndDecrement(): The value is decremented and its previous value is returned.

Example

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
 
public class AtomicIntegerTest {
  private static AtomicInteger num = new AtomicInteger();
  public static void main(String[] args) throws InterruptedException {
	  for (int i = 0; i < 10; i++) {
          num.set(0);
          ExecutorService es = Executors.newFixedThreadPool(2);
          es.execute(() -> {
              for (int j = 0; j < 1000; j++) {
                  num.incrementAndGet();
              }
          });
          es.execute(() -> {
              for (int j = 0; j < 1000; j++) {
                  num.incrementAndGet();
              }
          });
 
          es.shutdown();
          es.awaitTermination(10, TimeUnit.MINUTES);
          System.out.println(num.get());
      }
  }
}

Output

2000
2000
2000
2000
2000
2000
2000
2000
2000
2000
Content Protection by DMCA.com
Please Share