Sobes.tech
Junior — Middle

Have you had experience using the ThreadLocal class in your projects?

sobes.tech AI

Answer from AI

The ThreadLocal class in Java is used to store data that is 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.

Example of using ThreadLocal:

public class ThreadLocalExample {
    private static ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 0);

    public static void main(String[] args) {
        Runnable task = () -> {
            int value = threadLocal.get();
            value += 1;
            threadLocal.set(value);
            System.out.println(Thread.currentThread().getName() + " - " + threadLocal.get());
        };

        Thread thread1 = new Thread(task, "Thread 1");
        Thread thread2 = new Thread(task, "Thread 2");

        thread1.start();
        thread2.start();
    }
}

In this example, each thread has its own copy of the variable, and changes in one thread do not affect the other. ThreadLocal is useful when you need to store thread-specific state, such as in multi-threaded applications for storing user context or database connection.

Have you had experience using the ThreadLocal class… - sobes.tech