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.
Does AtomicInteger provide any kind of fairness guarantee? like first-come-first-serve execution order of threads
Share
No, there is no such guarantee. If there was one, it would be spelled out in the documentation.
When you think about it,
AtomicIntegeris 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 ofAtomicInteger.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.