Atomic variables and lock-free programming
15 questions in 5 subtopics.
AtomicInteger and AtomicReference
What doupdateAndGet and accumulateAndGet do on AtomicInteger, and what rule must the function follow?Fix the race in this code that should allow at most 100 concurrent jobs:if (running.get() < 100) {
running.incrementAndGet();
startJob();
}
AtomicInteger.An object holds three related fields (limit, used, windowStart) that must be updated together by many threads for a rate limiter. Compare an AtomicReference to an immutable state object with a lock.Compare-and-set
How doescompareAndSet work in hardware and in the JVM, and what is weakCompareAndSet for?A global sequence generator uses AtomicLong.incrementAndGet and is called by 64 threads at very high rates. Profiling shows CPU time in the increment. Explain the cost and options.Some libraries your services depend on still use sun.misc.Unsafe for CAS and off-heap memory. The JDK deprecated Unsafe memory-access methods for removal and now warns on their use. How would you plan for this across the organisation?LongAdder
How doesLongAdder differ from AtomicLong, and when should you use each?You are adding per-endpoint request counters and a max-latency gauge to a service doing 100,000 requests per second across 32 cores. Which classes would you use and why?Your platform team is building a shared metrics library used by every service. Hot paths record counters and timers at very high rates. Describe the concurrency design and the rules for teams using it.ABA problem
Explain the ABA problem with a lock-free stack example, and how Java helps or does not help.A team is building a pooled-object, lock-free buffer manager to reduce GC in a low-latency service, reusing node objects. In design review, what concerns would you raise about ABA and maintainability?The ABA problem in compare-and-set has a counterpart in distributed systems: optimistic concurrency with version numbers and HTTP ETags with If-Match. What lessons carry over, and what long-term stance on optimistic concurrency in your service APIs would you take?Lock-free data structures
Implement push and pop for a lock-free stack (Treiber stack) usingAtomicReference and explain why it is correct.An engineer proposes writing a custom lock-free queue for an important service because ConcurrentLinkedQueue showed up in a profile. How do you evaluate the proposal and what conditions would you set?Core counts keep rising, ARM servers are common, and NUMA effects matter on large machines. Over the next decade, which concurrency approaches should your organisation prefer: locks, atomics and lock-free structures, or designs based on partitioning and message passing? Explain your reasoning.No question matches these choices.