Skip to content

AtomicIntegerFieldUpdater

AtomicIntegerFieldUpdater is a utility class in Java used to perform atomic operations on a specific volatile int field within a class.^[600-developer-big-data-netty-netty-rotate.md, 600-developer__big-data__netty__netty-rotate.md]

Declaration and Instantiation

The updater is created using the newUpdater static factory method.^[600-developer-big-data-netty-netty-rotate.md, 600-developer__big-data__netty__netty-rotate.md] This method requires two arguments:

  1. The Class object containing the field.
  2. The String name of the field to be updated.

For example, in the AbstractReferenceCountedByteBuf class, the updater is initialized as follows:

private static final AtomicIntegerFieldUpdater<AbstractReferenceCountedByteBuf> refCntUpdater =
        AtomicIntegerFieldUpdater.newUpdater(AbstractReferenceCountedByteBuf.class, "refCnt");

^[600-developer-big-data-netty-netty-rotate.md, 600-developer__big-data__netty__netty-rotate.md]

Target Field Requirements

For the updater to function correctly, the target field must be declared with the volatile modifier.^[600-developer-big-data-netty-netty-rotate.md, 600-developer__big-data__netty__netty-rotate.md] In usage scenarios such as Reference counting, the field is typically initialized to a starting value, such as 1.^[600-developer-big-data-netty-netty-rotate.md, 600-developer__big-data__netty__netty-rotate.md]

Operations

Once defined, the updater can be used to perform atomic reads and writes on the target field using the compareAndSet method.^[600-developer-big-data-netty-netty-rotate.md, 600-developer__big-data__netty__netty-rotate.md]

This is commonly implemented within loops to handle concurrency, retrying the operation until the atomic update is successful.^[600-developer-big-data-netty-netty-rotate.md, 600-developer__big-data__netty__netty-rotate.md]

For instance, to atomically increment a reference count:

if (refCntUpdater.compareAndSet(this, refCnt, nextCnt)) {
    break;
}

^[600-developer-big-data-netty-netty-rotate.md, 600-developer__big-data__netty__netty-rotate.md]

Sources

  • 600-developer-big-data-netty-netty-rotate.md
  • 600-developer__big-data__netty__netty-rotate.md
  • [[AtomicInteger]]
  • [[Compare-And-Swap]]
  • [[Netty]]