Java SE API

AtomicInteger.incrementAndGet()

Atomically increment and return the updated value.

Formal Syntax & Structure

java syntaxjava
int incrementAndGet()

Working Example

Example Snippetjava
import java.util.concurrent.*;import java.util.concurrent.atomic.*;import java.util.concurrent.locks.*;public class Main {    static ThreadPoolExecutor pool(int workers, int capacity) {        return new ThreadPoolExecutor(workers, workers, 0, TimeUnit.SECONDS,            new ArrayBlockingQueue<>(capacity), new ThreadPoolExecutor.AbortPolicy());    }    static void stop(ExecutorService pool) throws InterruptedException {        pool.shutdown();        try {            if (!pool.awaitTermination(3, TimeUnit.SECONDS)) {                for (Runnable pending : pool.shutdownNow()) {                    if (pending instanceof Future<?> future) future.cancel(false);                }                if (!pool.awaitTermination(3, TimeUnit.SECONDS)) throw new AssertionError("workers still running");            }        } catch (InterruptedException e) {            for (Runnable pending : pool.shutdownNow()) {                if (pending instanceof Future<?> future) future.cancel(false);            }            throw e;        }    }    public static void main(String[] args) throws Exception {        AtomicInteger completed = new AtomicInteger();        LongAdder metrics = new LongAdder();        ThreadPoolExecutor workers = pool(2, 2);        Runnable job = () -> { for (int i = 0; i < 100; i++) { completed.incrementAndGet(); metrics.increment(); } };        try {            Future<?> a = workers.submit(job), b = workers.submit(job);            a.get(3, TimeUnit.SECONDS); b.get(3, TimeUnit.SECONDS);            System.out.println(completed.get());            System.out.println(metrics.sum());            System.out.println(completed.compareAndSet(200, 201));            System.out.println(completed.get());        } finally { stop(workers); }    }}
Java Reference