atomiclong in java

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

Creating an AtomicLong

AtomicLong atomicLong = new AtomicLong();

Create an atomic long with the default value 0.

AtomicLong atomicLong = new AtomicLong(453);

Create an atomic long with the initial value 453.

Commonly used methods of AtomicLong class

  • get(): Reads the value atomically.
  • set(long newValue): Writes the value atomically.
  • compareAndSet(long expect, long 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(long delta): The delta is added to the value and the new value is returned.
  • getAndAdd(long 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.AtomicLong;
 
public class AtomicLongTest {
  private static AtomicLong result = new AtomicLong();
  public static void main(String[] args) throws InterruptedException {
	for (int i = 0; i < 5; i++) {
          result.set(0);
          ExecutorService es = Executors.newFixedThreadPool(50);
          for (int j = 1; j <= 20; j++) {
              int finalI = j;
              es.execute(() -> {
            	  result.addAndGet((long) Math.pow(2, finalI));
              });
          }
          es.shutdown();
          es.awaitTermination(10, TimeUnit.MINUTES);
          System.out.println(result);
      }
  }
}

Output

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