ThreadLocal은 쓰레드당 접근 가능한 데이터를 저장하도록 해주는 API이다
예를 들어 Integer 타입의 값을 저장하고 싶으면 아래와 같이 ThreadLocal을 선언하면 된다.
ThreadLocal<Integer> threadLocalValue = new ThreadLocal<>();
값의 저장과 조회는 get(), set() 메서드를 통해서 수행할 수 있다.
threadLocalValue.set(1); // 1을 저장
Integer result = threadLocalValue.get(); // 해당 쓰레드에 저장되어 있는 값을 조회 -> 1
ThreadLocal.withInitial() 메소드를 이용하면 ThreadLocal 생성 시 초기값을 지정할 수 있다.
ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 1);
ThreadLocal에서 값을 삭제하고 싶으면 remove() 메소드를 사용하면 된다.
threadLocal.remove();
다음으로는 간단한 예제를 통해 TreadLocal을 어떻게 사용할 수 있는지 알아보도록 하겠다.
우선 아래와 같이 user 정보를 담는 Context 클래스를 정의한다.
public class Context {
private String userName;
public Context(String userName) {
this.userName = userName;
}
}
user id 당 한개의 thread가 사용되도록 하고 싶다. 이를 위하여 SharedMapWithUserContext 클래스를 정의한다.
public class ThreadLocalWithUserContext implements Runnable {
private static ThreadLocal<Context> userContext = new ThreadLocal<>();
private Integer userId;
private UserRepository userRepository = new UserRepository();
@Override
public void run() {
String userName = userRepository.getUserNameForUserId(userId);
userContext.set(new Context(userName));
System.out.println("thread context for given userId: "
+ userId + " is: " + userContext.get());
}
// standard constructor
}
아래와 같이 테스트 코드를 작성한 후 결과를 아래와 같다.
ThreadLocalWithUserContext firstUser = new ThreadLocalWithUserContext(1);
ThreadLocalWithUserContext secondUser = new ThreadLocalWithUserContext(2);
new Thread(firstUser).start();
new Thread(secondUser).start();
thread context for given userId: 1 is: Context{userNameSecret='18a78f8e-24d2-4abf-91d6-79eaa198123f'}
thread context for given userId: 2 is: Context{userNameSecret='e19f6a0a-253e-423e-8b2b-bca1f471ae5c'}
콘솔 결과를 보면 user id 당 한개의 Context가 할당되었음을 알 수 있다.
주의할 점은 ThreadLocal을 사용한 후 remove() 메소드를 사용하며 저장된 값을 적절히 제거해줘야 합니다.
Concurrent Random Number (0) | 2024.09.24 |
---|---|
[자바 성능 튜닝] 성능 테스트 접근법 (0) | 2024.04.07 |
JVM 메모리 관리 (0) | 2023.05.29 |
Stream API 개요 (0) | 2023.05.05 |
CompletableFuture get()과 join()의 차이점 (0) | 2023.05.02 |
댓글 영역