Thread Safety With AtomicInteger
Consider the following AtomicRecursive class. Why is AtomicInteger the appropriate choice for the counter variable instead of a volatile int?
import java.util.concurrent.atomic.AtomicInteger;
public class AtomicRecursive {
private static AtomicInteger counter = new AtomicInteger(0);
public static void recursiveIncrement(int n) {
if(n <= 0) return;
counter.getAndIncrement();
new Thread(() -> recursiveIncrement(n - 1)).start();
}
public static void main(String[] args) throws InterruptedException {
recursiveIncrement(5);
Thread.sleep(1000);
System.out.println("Counter: " + counter.get());
}
}
A
Both volatile int and AtomicInteger offer the same thread safety for compound operations.
B
AtomicInteger is only used to improve performance, not for thread-safety.
C
AtomicInteger provides atomic operations for increments, ensuring thread-safety for compound actions, which volatile does not guarantee.
D
A volatile int automatically handles atomic increments, making AtomicInteger redundant.
Question Leaderboard
Not enough data yet to show leaderboard.
