Atomic variables in Java


Yes, from Java 8 onwards, java.util.concurrent.atomic package contains classes which support atomic operations on single variables preventing race conditions or do not face synchronization issues. All classes in the atomic package have get/set methods. Each set method has a happens-before relationship with any subsequent get() method call on the same variable.

import java.util.concurrent.atomic.AtomicInteger;

class AtomicCounter {
   private AtomicInteger counter = new AtomicInteger(0);
   
   public void increment() {
      counter.incrementAndGet();
   }
   public void decrement() {
      counter.decrementAndGet();
   }
   public int value() {
      return counter.get();
   }
}

Updated on: 30-Jul-2019

120 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements