Search code examples
javaintegeratomic

Is AtomicInteger fair?


Does AtomicInteger provide any kind of fairness guarantee? like first-come-first-serve execution order of threads on it? The animated example at Victor Grazi's concurrent animated definitely does not show any such fairness. I've searched and haven't found anything conclusive.


Solution

  • No, there is no such guarantee. If there was one, it would be spelled out in the documentation.

    When you think about it, AtomicInteger is basically a thin wrapper around compare-and-swap (or similar). Guaranteeing first-come-first-served semantics would require synchronization between threads, which is costly, and contrary to the very idea of AtomicInteger.

    The way things are is that if there are multiple threads wanting to, say, incrementAndGet() the same atomic integer concurrently, the order in which they finish the race is unspecified.