lottie
Seungjun's blog
blog
ThreadLocal

ThreadLocal은 Java에서 다중 스레드 환경에서 사용되는 데이터 공유의 한 형태입니다. 각 스레드가 자체적으로 값을 저장하고 가져올 수 있는 저장소를 제공합니다.

이는 동일한 코드에서 여러 스레드가 실행될 때 각 스레드에 대해 고유한 값을 가질 수 있게 해줍니다.


ThreadLocal은 java.lang 패키지에 속한 클래스로, 다음과 같은 주요 메서드를 제공합니다:

  1. get() : 현재 스레드에 연결된 값(쓰레드 로컬 값)을 반환합니다.

  2. set(T value) : 현재 스레드에 연결된 값을 설정합니다.

  3. remove() : 현재 스레드에 연결된 값을 제거합니다.


    예시 코드

public class ExampleThreadLocal {

    // ThreadLocal을 선언하고 초기값을 제공합니다.
    private static final ThreadLocal<String> threadLocalValue = new ThreadLocal<String>() {
        @Override
        protected String initialValue() {
            return "Default Value";
        }
    };

    public static void main(String[] args) {
        // 각각의 스레드에서 ThreadLocal 값을 가져오기
        Thread thread1 = new Thread(() -> {
            System.out.println("Thread 1 - Initial Value: " + threadLocalValue.get());

            // ThreadLocal 값을 변경
            threadLocalValue.set("New Value");

            // 변경된 ThreadLocal 값을 가져오기
            System.out.println("Thread 1 - Updated Value: " + threadLocalValue.get());
        });

        Thread thread2 = new Thread(() -> {
            System.out.println("Thread 2 - Initial Value: " + threadLocalValue.get());
        });

        // 스레드 시작
        thread1.start();
        thread2.start();
    }
}

이 예시에서 threadLocalValue는 ThreadLocal 객체입니다.

각 스레드에서 threadLocalValue.get()을 호출하면 현재 스레드에 연결된 값을 가져올 수 있습니다. threadLocalValue.set("New Value")를 통해 현재 스레드에 새로운 값을 설정할 수 있습니다.


ThreadLocal은 보통 각 스레드에 대한 정보를 저장하는 데 사용되며, 스레드 간에 공유되지 않고 독립적인 변수를 가지게 해줍니다.

주의할 점은 ThreadLocal을 사용할 때 메모리 누수에 주의해야하며, 더 이상 사용되지 않는 데이터는 remove() 메서드를 사용하여 정리하는 것이 좋습니다.