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:
- The
Classobject containing the field. - The
Stringname 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.md600-developer__big-data__netty__netty-rotate.md
Related Concepts¶
- [[AtomicInteger]]
- [[Compare-And-Swap]]
- [[Netty]]