JavaIntermediate#concurrency

What are atomic classes like AtomicInteger used for?

They provide lock-free, thread-safe operations on single variables using CAS (compare-and-swap) hardware instructions, avoiding the overhead of synchronized blocks for simple counters or flags.

Example
AtomicInteger counter = new AtomicInteger(0);
counter.incrementAndGet();
counter.compareAndSet(1, 5); // sets to 5 only if current value is 1

Related Questions

1
JavaAdvanced#concurrency

What is a CountDownLatch?

Open
2
JavaAdvanced#concurrency

What is a ThreadLocal and when would you use it?

Open
3
JavaIntermediate#concurrency

What is the difference between Thread.sleep() and Object.wait()?

Open