Volatile Keyword Guarantees in Java
In the VolatileRecursive class shown below, the count variable is declared as volatile. Which statement best describes the guarantees and limitations of this keyword in the context of the recursiveIncrement method?
public class VolatileRecursive {
private static volatile int count = 0;
public static void recursiveIncrement(int n) {
if(n <= 0) return;
count = count + 1;
new Thread(() -> recursiveIncrement(n - 1)).start();
}
public static void main(String[] args) throws InterruptedException {
recursiveIncrement(5);
Thread.sleep(1000);
System.out.println("Count: " + count);
}
}
A
Volatile guarantees both visibility and atomicity, ensuring that the count is correctly incremented.
B
Volatile prevents any concurrency issues by serializing access to the variable.
C
Volatile guarantees visibility of the variable across threads but does not ensure atomicity of compound operations like incrementing.
D
Volatile has no effect in a recursive method as thread communications are not involved.
Question Leaderboard
Not enough data yet to show leaderboard.
APFIVE