# Using AtomicReference and testAndSet for Concurrency Management

A solution for thread safety with AtomicReference and a custom testAndSet function.

- **Source:** [Public Object](https://brifing.si/source/eac99d4a-0c38-4b6e-908d-b16fae99f31a)
- **Published:** 2026-07-13
- **Topic:** [Software & Engineering](https://brifing.si/c/engineering)
- **Original article:** <https://publicobject.com/2026/07/13/test-set/>
- **On Brifing:** https://brifing.si/s/bee10704-3c64-4b45-be69-b3b53ab8e4fc

## Thread Safety and AtomicReference

Working with threads makes deterministic testing challenging. AtomicReference provides a reliable solution with its concurrency power and simple API. However, updates often require a while loop, increasing code complexity.

## compareAndSet and Retry Mechanism

AtomicReference's compareAndSet function returns false if the thread loses a race, requiring retries. This leads to complex loops in the code, especially when business logic and concurrency code are intertwined, reducing readability.

## Developing the testAndSet Function

The testAndSet function was developed to simplify AtomicReference's complex loops. By returning the previous value, it separates business logic from concurrency code, resulting in cleaner and more understandable code.

## Function Signature and Design

Determining the signature for testAndSet was challenging. The decision to return the previous value made everything fall into place. Using tailrec instead of traditional loops provided a more elegant solution.

## Separation of Business and Concurrency Logic

The testAndSet function successfully separates business logic from concurrency code. This allows complex business rules and thread management to be handled independently, greatly improving code maintainability and readability.

## Conclusion and Benefits

The testAndSet function simplifies AtomicReference usage, enabling safer and more readable code. It minimizes concurrency errors while allowing business logic to be expressed clearly. This approach offers significant advantages in projects requiring thread safety.

## Sources covering this story

- https://publicobject.com/2026/07/13/test-set/ — 

---

_Summary written by Brifing from the original reporting. Copyright in the original article belongs to its publisher; read the full piece at the link above._
