Java Thread Tutorial - Java Atomic Variables








New Thread Concurrency Packages

java.util.concurrent, and java.util.concurrent.atomic and java.util.concurrent.locks include very useful concurrency constructs.

The Thread Concurrency Packages support the concurrency in four ways.

  • Atomic variables
  • Locks
  • Synchronizers
  • Concurrent collections




Atomic Variables

Atomic variable classes are named like AtomicXxx, for example, AtomicInteger class is used to represent an int variable.

Atomic variable can be used to execute multiple instructions on a single variable atomically without using any lock.

  • Scalar Atomic Variable Classes

    The AtomicInteger, AtomicLong, and AtomicBoolean classes support operations on primitive data types int, long, and boolean, respectively.

    The AtomicReference class is used to work with a reference data type when a reference variable needs to be updated atomically.

  • Atomic Arrays Classes

    There are three classes called AtomicIntegerArray, AtomicLongArray, and AtomicReferenceArray that represent an array of int, long, and reference types whose elements can be updated atomically.

  • Atomic Field Updater Classes

    There are three classes called AtomicLongFieldUpdater, AtomicIntegerFieldUpdater, and AtomicReferenceFieldUpdater that can be used to update a volatile field of a class atomically using reflection.

    To get a reference to an object of these classes, you need to use their factory method called newUpdater().

  • Atomic Compound Variable Classes




Example

The following code shows how to use the AtomicLong class to create a Counter.

import java.util.concurrent.atomic.AtomicLong;

public class AtomicCounter {
  private AtomicLong value = new AtomicLong(0L);

  public long next() {
    return value.incrementAndGet();
  }
}