← Back to libraryQuestion 35 of 273
JavaAdvanced

Atomic Variables and CAS

📖 Detailed Explanation:

Atomic variables (AtomicInteger, AtomicLong) use CPU-level 'Compare-And-Swap' (CAS) instructions to perform thread-safe operations WITHOUT heavy locking overhead. CAS checks if the current value matches an expected value; if yes, it updates atomically; if no, it retries. This is much faster than synchronized blocks.

🌍 Real-World Example:

A ticket counter: The machine checks if you have the right numbered ticket stub. If yes, it gives you a number and advances. If no (someone else already took it), it tells you to try again.

🎯 Scenario-Based Interview Question:

What is CAS (Compare-And-Swap) and how does it work? Why is it faster than synchronized?