Java / Java 21 Interview Questions
What are the java.util.concurrent.atomic classes and how do they work?
The java.util.concurrent.atomic package provides lock-free, thread-safe single-variable operations using CPU-level Compare-And-Swap (CAS) instructions. They are faster than synchronized blocks for single-variable updates because they avoid locking entirely.
// AtomicInteger — counter safe for use from multiple threads
AtomicInteger counter = new AtomicInteger(0);
counter.incrementAndGet(); // returns new value: 1
counter.getAndIncrement(); // returns old value: 1, new value: 2
counter.addAndGet(5); // atomically add 5
counter.compareAndSet(7, 0); // only updates if current == 7
// AtomicLong, AtomicBoolean, AtomicReference work the same way
// AtomicReference — CAS on an object reference
AtomicReference name = new AtomicReference<>("initial");
boolean updated = name.compareAndSet("initial", "updated"); // true
// LongAdder — better than AtomicLong under HIGH contention
LongAdder hitCount = new LongAdder();
hitCount.increment(); // thread-safe, very fast under contention
long total = hitCount.sum(); // reads the aggregate
// LongAdder splits the counter across multiple cells to reduce contention
// AtomicIntegerArray, AtomicLongArray, AtomicReferenceArray
AtomicIntegerArray arr = new AtomicIntegerArray(10);
arr.compareAndSet(5, 0, 99); // CAS on index 5
// VarHandle (Java 9) — generalized CAS on any field
// More powerful but more verbose than atomic classes LongAdder vs AtomicLong: at low contention they perform similarly. Under high contention (many threads incrementing simultaneously), LongAdder is significantly faster because it distributes the counter across multiple cells and only aggregates in sum(). Use LongAdder for pure counters; use AtomicLong when you need atomic read-modify-write with a precise current value (e.g., compareAndSet patterns).
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
