Thread Safety With AtomicInteger
Why is AtomicInteger preferred over a volatile int in this recursive multithreaded context?
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
AtomicInteger is only used to improve performance, not for thread-safety.
B
Both volatile int and AtomicInteger offer the same thread safety for compound operations.
C
A volatile int automatically handles atomic increments, making AtomicInteger redundant.
D
AtomicInteger provides atomic operations for increments, ensuring thread-safety for compound actions, which volatile does not guarantee.
Question Leaderboard
Not enough data yet to show leaderboard.
APFIVE