ThreadLocal은 Java에서 각 스레드가 고유하게 사용할 수 있는 변수를 제공하는 클래스입니다. 이 변수를 통해 각 스레드가 독립적인 값을 가질 수 있으며, 다른 스레드와 공유하지 않습니다. 이를 통해 동시성 문제를 해결할 수 있습니다.
고유한 변수:
동시성 문제 해결:
간편한 사용:
ThreadLocal 클래스는 간편한 API를 제공하여 쉽게 사용할 수 있습니다.set(), get(), remove() 메서드를 통해 값을 설정, 조회, 삭제할 수 있습니다.여러 스레드가 동시에 실행되며 각 스레드가 고유한 사용자 ID를 관리하는 프로그램을 생각해 봅시다. ThreadLocal을 사용하지 않으면, 모든 스레드가 동일한 변수를 공유하게 되어 문제가 발생할 수 있습니다. 하지만 ThreadLocal을 사용하면 각 스레드가 자신만의 사용자 ID를 안전하게 관리할 수 있습니다.
public class ThreadLocalExample {
// ThreadLocal 변수를 선언하여 각 스레드가 고유한 Integer 값을 가질 수 있도록 합니다.
private static ThreadLocal<Integer> userId = ThreadLocal.withInitial(() -> 0);
public static void main(String[] args) {
Runnable task = () -> {
// 스레드마다 고유한 값을 설정하고 출력합니다.
int currentUserId = userId.get();
System.out.println(Thread.currentThread().getName() + " initial userId: " + currentUserId);
// 사용자 ID를 스레드별로 증가시킵니다.
userId.set(currentUserId + 1);
// 업데이트된 값을 출력합니다.
System.out.println(Thread.currentThread().getName() + " updated userId: " + userId.get());
};
// 두 개의 스레드를 생성하고 실행합니다.
Thread thread1 = new Thread(task, "Thread-1");
Thread thread2 = new Thread(task, "Thread-2");
thread1.start();
thread2.start();
}
}
ThreadLocal 변수 선언:
private static ThreadLocal<Integer> userId = ThreadLocal.withInitial(() -> 0);
ThreadLocal.withInitial(() -> 0)을 사용하여 초기값을 0으로 설정합니다. 이렇게 하면 각 스레드는 처음에 0 값을 가지게 됩니다.
Runnable 구현:
Runnable task = () -> {
int currentUserId = userId.get();
System.out.println(Thread.currentThread().getName() + " initial userId: " + currentUserId);
userId.set(currentUserId + 1);
System.out.println(Thread.currentThread().getName() + " updated userId: " + userId.get());
};
각 스레드가 실행할 작업을 정의합니다. 처음에는 userId의 현재 값을 가져와 출력하고, 그 값을 1 증가시킨 후 다시 출력합니다.
스레드 생성 및 실행:
Thread thread1 = new Thread(task, "Thread-1");
Thread thread2 = new Thread(task, "Thread-2");
thread1.start();
thread2.start();
두 개의 스레드를 생성하고 실행합니다. 각 스레드는 task를 실행하게 됩니다.
Thread-1 initial userId: 0
Thread-2 initial userId: 0
Thread-1 updated userId: 1
Thread-2 updated userId: 1
각 스레드는 독립적으로 userId를 관리하므로 초기값이 0이며, 이후 값을 1로 업데이트합니다. 서로의 값에 영향을 주지 않습니다.
ThreadLocal을 사용하면 스레드마다 고유한 변수를 가질 수 있어 동시성 문제를 피할 수 있습니다. 위 예제에서는 각 스레드가 독립적으로 사용자 ID를 관리하도록 하여, 서로 간섭하지 않고 안전하게 값을 변경할 수 있음을 보여줍니다.