I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

1. Overview

2. Why Do We Need AtomicStampedReference?

First, AtomicStampedReference provides us with both an object reference variable and a stamp that we can read and write atomically. We can think of the stamp a bit like a timestamp or a version number.

Simply put, adding a stampallows us to detect when another thread has changed the shared reference from the original reference A, to a new reference B, and back to the original reference A.

Let's see how it behaves in practice.

3. Bank Account Example

Consider a bank account that has two pieces of data: a balance and a last modified date. The last modified date is updated any time the balance is altered. By observing this last modified date, we can know the account has been updated.

The compareAndSet method returns a boolean indicating success or failure. A failure means that either the balance or the stamp has changed since we last read it.

As we can see, it's easy to retrieve the reference and the stamp using their getters.

But, as mentioned above, we need the latest version of them when we want to update their values using the CAS. To retrieve those two pieces of information atomically, we need to fetch them at the same time.

Luckily, AtomicStampedReference provides us an array-based API to achieve this. Let's demonstrate its usage by implementing the withdrawal() method for our Account class:

3.4. Choosing the Next Stamp

Semantically, the stamp is like a timestamp or a version number, so it's typically always increasing. It's also possible to use a random number generator.

The reason for this is that, if the stamp can be changed to something it was previously, this could defeat the purpose of AtomicStampedReference.AtomicStampedReference itself doesn't enforce this constraint, so it's up to us to follow this practice.

4. Conclusion

In conclusion, AtomicStampedReference is a powerful concurrency utility that provides both a reference and a stamp that can be read and updated atomically. It was designed for A-B-A detection and should be preferred to other concurrency classes such as AtomicReference where the A-B-A problem is a concern.