Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

AtomicLong: initial value and atomic increment

Set the starting value of a shared counter, retrieve each number after incrementing, and see why the `POISON` sentinel gets the lowest number.

Version: Java SE 21

Syntax

import java.util.concurrent.atomic.AtomicLong;

// Constructor: public AtomicLong(long initialValue)
// Instance method: public final long incrementAndGet()
AtomicLong seq = new AtomicLong(40L);
long next = seq.incrementAndGet();

In Java SE 21, AtomicLong in java.util.concurrent.atomic holds one mutable long value. AtomicLong(long) creates a new counter with the supplied initial value; the AtomicLong() overload starts at 0. The initial value is not yet the first assigned number.

AtomicLong.incrementAndGet is a no-argument instance method. In one atomic operation, it adds 1 and returns the updated long. getAndIncrement() also increments the counter but returns the previous value. The read and write have volatile memory semantics, as specified by VarHandle.getAndAdd.

If threads only increment the same instance, assigned numbers are distinct and strictly increase in update order until overflow. After Long.MAX_VALUE, the next value is Long.MIN_VALUE, without an exception. The counter does not make object construction or queue insertion atomic, nor does it determine the order in which threads finish their work.

The static field initializers in the example run in source order. The shared counter SEQ is created first, then the sentinel POISON. Its constructor performs the first increment and stores 41, the lowest number in the example. The regular entries are created later in main.

Examples

import java.util.concurrent.atomic.AtomicLong;

public class SequenceDemo {
    private static final AtomicLong SEQ = new AtomicLong(40L);
    private static final Entry POISON = new Entry();

    private static final class Entry {
        private final long seq;

        private Entry() {
            seq = SEQ.incrementAndGet();
        }
    }

    public static void main(String[] args) {
        Entry first = new Entry();
        Entry second = new Entry();
        System.out.println("POISON: " + POISON.seq);
        System.out.println("first: " + first.seq);
        System.out.println("second: " + second.seq);
    }
}

Result

POISON: 41
first: 42
second: 43

This is a single-threaded demonstration: `40` is the starting value, and `41`, `42`, and `43` are the numbers returned by successive increments.

Related lessons

  • Java · Lesson 38 · Advanced · Version: 2

Sources