Pick the fix
Two threads each run hits++ 10,000 times on a @Volatile var hits = 0. The total is often below 20,000. Fix?
Hint 1 of 1
Is ++ one step or three?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A Use AtomicInteger.incrementAndGet() or a synchronized block
Correct. The increment must be atomic, not just visible.
Why not the others?
- B Mark it @Volatile twice. Not a thing, and volatile isn't the problem.
- C Make it a val. Then it can't change.
- D Add Thread.sleep between increments. Hides the race sometimes.