Sobes.tech
Junior — Middle

Can you explain the purpose and operation of the ThreadLocal class in Java?

sobes.tech AI

Answer from AI

The ThreadLocal class in Java is used to create variables that are unique to each thread. This means that each thread has its own copy of the variable, and changes in one thread do not affect the values in others.

This is useful when you want to avoid issues with concurrent access to shared data without using synchronization.

Example of usage:

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

// In each thread, you can do the following:
int counter = threadLocalCounter.get();
counter++;
threadLocalCounter.set(counter);

Thus, each thread works with its own version of counter.