Atomic Integer handles concurrency smartly & efficiently

Atomic integer is used to handle concurrency of increment and decrement operation smartly using a non-blocking algorithm.

Also it improves the execution time when compared to synchronized way of handling concurrency.

import java.util.concurrent.atomic.AtomicInteger;
public class AtomicIntegerTest {
 public static void main(String[] args) {
  AtomicInteger counter = new AtomicInteger(0);
  for(int i=0; i<50; i++) {
   Runnable runnable = new WorkerThread(counter);
   Thread t = new Thread(runnable);
   t.start();
  }
 }
}
class WorkerThread implements Runnable {
 AtomicInteger count = null;
 WorkerThread(AtomicInteger counter) {
  this.count = counter;
 }
 public void run() {
  int value = this.count.incrementAndGet();
  System.out.println(value);
 }
}

 Above problem spans 50 threads and does increment operation.

You can notice that it prints number between 1 and 50 without a duplicate value which ensures the concurrency.

Advertisements