Atomic variables in Java

Java Programming Java8Object Oriented ProgrammingJava Technologies

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();
   }
}
raja
Published on 22-Jan-2018 05:35:44
Advertisements