Sobes.tech
Junior — Middle

What distinguishes a standard variable from a variable implemented through ThreadLocal?

sobes.tech AI

Answer from AI

A standard variable in Java is shared among all threads if it is static, or local to an object/method, but accessing it from different threads can lead to race conditions.

ThreadLocal is a special class that allows each thread to have its own, independent copy of a variable. This means that the value stored in ThreadLocal is unique to each thread and does not intersect with others.

Example of using ThreadLocal:

ThreadLocal<Integer> threadLocalValue = ThreadLocal.withInitial(() -> 0);

// In each thread, you can get and modify its value:
int value = threadLocalValue.get();
threadLocalValue.set(value + 1);

This is useful when you need to store thread-specific state without synchronization and the risk of conflicts between threads.

What distinguishes a standard variable from a… - sobes.tech