AtomicStampedReference
Learn how the AtomicStampedReference class can be used to address the ABA problem that can manifest when classes manage their own memory.
We'll cover the following...
If you are interviewing, consider buying our number#1 course for Java Multithreading Interviews.
Overview
Similar to the AtomicReference
class, the AtomicStampedReference
class contains a reference to an object and additionally an integer stamp. The integer stamp is usually incremented whenever the object pointed to by the reference is modified. The AtomicStampedReference
class can be thought of as a generalization of the AtomicMarkableReference
class, replacing the boolean with an integer. The integer stamp stored alongside the reference can also be used for other purposes such as maintaining one of the finite states a data structure can be in . The stamp and reference fields can be updated atomically, either together or individually.
The code widget below demonstrates the use of AtomicStampedReference
and its common APIs.
import java.util.concurrent.atomic.AtomicStampedReference;class Demonstration {public static void main( String args[] ) {Long myLong = new Long(3);Long anotherLong = new Long(7);// set the initial stamp to 1 and reference to myLongAtomicStampedReference<Long> atomicStampedReference = new AtomicStampedReference<>(myLong,1);// we attempt to change the object reference but use the incorrect stamp and the compareAndSet failsboolean result = atomicStampedReference.compareAndSet(myLong, anotherLong, 0, 1);System.out.println("Was compareAndSet() successful : " + result + " and object value is " + atomicStampedReference.getReference().toString());// we attempt compareAndSet again with the right expected stampresult = atomicStampedReference.compareAndSet(myLong, anotherLong, 1, 2);System.out.println("Was compareAndSet() successful : " + result + " and object value is " + atomicStampedReference.getReference().toString());// Retrieve the current stamp and reference using the get() methodint[] currStamp = new int[1];Long reference = atomicStampedReference.get(currStamp);System.out.println("current stamp " + currStamp[0] + " reference value " + reference.toString());}}
Note that the current reference and stamp can ...