Java ThreadLocal Variable Behavior
What is the consequence of using ThreadLocal for counter management in this multithreaded example?
public class ThreadLocalExample {
private static ThreadLocal<Integer> threadLocalCounter = ThreadLocal.withInitial(() -> 0);
public static void increment() {
threadLocalCounter.set(threadLocalCounter.get() + 1);
}
public static int get() {
return threadLocalCounter.get();
}
}
A
Each thread maintains its own counter, so there is no shared aggregation across threads.
B
An exception is thrown because ThreadLocal cannot be used with numeric values.
C
A race condition occurs because each thread updates the same global counter simultaneously.
D
Deadlock happens when threads wait for access to the ThreadLocal variable.
Question Leaderboard
Not enough data yet to show leaderboard.
APFIVE