Concurrency basics · interview question
Which changes would make the counter in a multi-threaded increment loop correct? Select all that apply.
Select all that applyMedium
Answer and explanation
Correct answer
- A. Use an
AtomicIntegerand callincrementAndGet(). - B. Do the increment inside a
synchronizedblock on a shared lock. - D. Use a
LongAdderand callincrement().
Why
Atomics use CAS instructions; synchronized provides mutual exclusion; LongAdder spreads contention across cells and is fastest under heavy write contention.
References
Test yourself on Concurrency basics
A free test with instant, explained results. No account needed.
More Concurrency basics questions
- Which method is used to wait for all CompletableFutures in a list to complete?
- How can you ensure that a CompletableFuture runs on a specific Executor?
- Which situation benefits most from using AtomicInteger over synchronized blocks?
- Which CompletableFuture method should be used to execute a task asynchronously in a non-blocking manner?
- In which scenario would you use.thenCompose() over.thenApply() in CompletableFuture?
- Which CompletableFuture method should be used to handle both results and exceptions in a unified way?