dev.mccue.async

What is it

dev.mccue.async provides one class - Atom. Atom wraps an AtomicReference and gives a simpler, if less powerful, API that is geared around atomic compare and swap operations.

Why use it

If you are from the Clojure world, this gives an API directly inspired by its atom construct. That can be appealing if you want to have managed immutable state and are used to that world.

The primary utility provided is having the atomic compare and swap logic already written out for you. It's only a handful of lines, but not something appealing to copy around a codebase.

Getting Started

import java.util.ArrayList;
import dev.mccue.async.Atom;

void main() throws Exception {
    var data = Atom.of(0);
    
    // 0
    System.out.println(data.get());
    
    data.swap(x -> x + 1);
    
    // 1
    System.out.println(data.get());
    
    // A bunch of concurrent swaps is sorta a worse
    // case situation for an atomic reference perf.
    // wise, but a good illustration of correctness.
    
    var threads = new ArrayList<Thread>();
    for (int i = 0; i < (10000 - 1); i++) {
        threads.add(
            Thread.startVirtualThread(() -> data.swap(x -> x + 1))
        );
    }
    
    for (var thread : threads) {
        thread.join();
    }
    
    // 10000
    System.out.println(data.get());
}

<- Index