Java ThreadLocal Variable Behavior
What is the primary consequence of using a ThreadLocal variable for counter management in the multithreaded example shown below?
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
An exception is thrown because ThreadLocal cannot be used with numeric values.
B
Each thread maintains its own counter, so there is no shared aggregation across threads.
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.
