Video in progress

Strong Middle 🧵 Concurrency

I need an atomic counter in each of millions of objects. Why would you choose AtomicLongFieldUpdater or VarHandle over an AtomicLong field?

Every AtomicLong is a separate object: a header, a reference and an extra indirection. A field updater or a VarHandle does CAS on a plain volatile long field, so it saves memory and follows one reference fewer. The price is more complex code that's easier to get wrong.

📖 Answer

The math: on a 64-bit JVM with compressed oops, an AtomicLong object is about 24 bytes, plus a 4-byte reference to it. With 10 million Connection objects, that's hundreds of MB. A plain long field is 8 bytes and lives inside the object itself.

final class Connection {
    private static final AtomicLongFieldUpdater<Connection> BYTES =
            AtomicLongFieldUpdater.newUpdater(Connection.class, "bytesSent");

    private volatile long bytesSent;          // must be volatile

    void onSend(int n) { BYTES.addAndGet(this, n); }
    long bytesSent()   { return bytesSent; }
}

In Java 9+ the modern variant is VarHandle:

private static final VarHandle BYTES;
static {
    try {
        BYTES = MethodHandles.lookup().findVarHandle(Connection.class, "bytesSent", long.class);
    } catch (ReflectiveOperationException e) { throw new ExceptionInInitializerError(e); }
}

void onSend(int n) { BYTES.getAndAdd(this, (long) n); }

The JDK itself does this: CompletableFuture, FutureTask and others have no separate atomic objects, and their fields are updated through VarHandle.

What to watch for:

  • the updater finds the field by name through reflection. If you rename the field or remove volatile, the error shows up at class initialization, not at compile time;
  • if you write to the field anywhere else with a plain bytesSent += n, atomicity breaks, so all writes should go through the updater;
  • the code gets harder to read, so keep this class small and well commented.

This optimization pays off when the number of objects is really large and the heap histogram (jcmd <pid> GC.class_histogram) shows AtomicLongs near the top. In an ordinary service, AtomicLong is easy to read and good enough.