AtomicMarkableReference

Learn to use the AtomicMarkableReference class for designing lock-free data structure such as linked-lists.

We'll cover the following...

If you are interviewing, consider buying our number#1 course for Java Multithreading Interviews.

Overview

The AtomicMarkedReference class is similar to the AtomicStampedReference class in that it holds a reference to an object but instead of an integer stamp it takes in a boolean value, called the mark. Both these fields can be updated atomically either together or individually. One could argue that AtomicStampedReference class would behave similarly to AtomicMarkableReference class if it accepted only two possible values for the integer stamp argument.

The code widget below demonstrates some of the basic operations when working with the AtomicMarkableReference class.

Press + to interact
import java.util.concurrent.atomic.AtomicMarkableReference;
class Demonstration {
public static void main( String args[] ) {
Long myLong = new Long(5);
Long anotherLong = new Long(7);
AtomicMarkableReference<Long> atomicMarkableReference = new AtomicMarkableReference<>(myLong, false);
// attempt to change the long value with the wrong expected mark
boolean wasSuccess = atomicMarkableReference.compareAndSet(myLong, anotherLong, true, true);
System.out.println("compare and set succeeded " + wasSuccess + " current value " + atomicMarkableReference.getReference());
// attempt to change the long value with the right expected mark
wasSuccess = atomicMarkableReference.compareAndSet(myLong, anotherLong, false, true);
System.out.println("compare and set succeeded " + wasSuccess + " current value " + atomicMarkableReference.getReference());
}
}

Example

AtomicMarkableReference can be put to good use when designing lock-free lists, such as a set representation backed by a ...