Spring 핵심원리 고급편 - ThreadLocal

목차

ThreadLocal

ThreadLocal은 해당 Thread 만 접근할 수 있는 저장소다
ThreadLocal을 사용하게 되면 각 Thread마다 별도의 저장소를 제공한다.

  • 사용법
    • 값 저장 : ThreadLocal.set(value)
    • 값 조회 : ThreadLocal.get()
    • 값 삭제 : ThreadLocal.remove()

해당 Thread 가 ThreadLocal 을 모두 사용하고 나면 ThreadLocal.remove() 를 호출해 ThreadLocal 에 저장된 값을 제거해 줘야 한다.

@Slf4j
public class ThreadLocalService {

private ThreadLocal<String> nameStore = new ThreadLocal<>();

public String logic(String name) {
log.info("저장 name={} -> nameStore = {}", name, nameStore.get());

nameStore.set(name);
sleep(1000);

log.info("조회 nameStore = {}", nameStore.get());

return nameStore.get();
}

private void sleep(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Slf4j
public class ThreadLocalServiceTest {

private ThreadLocalService service = new ThreadLocalService();


@Test
public void field(){
log.info("main start");
Runnable userA = () -> {
service.logic("userA");
};

Runnable userB = () -> {
service.logic("userB");
};

Thread threadA = new Thread(userA);
threadA.setName("thread - A");
Thread threadB = new Thread(userB);
threadB.setName("thread - B");

threadA.start();
sleep(100);
threadB.start();

sleep(2000); // 메인 Thread 종료 대기
}

private void sleep(int millis){
try {
Thread.sleep(millis);
}catch (Exception e){
e.printStackTrace();
}
}
}
15:09:42.290 [Test worker] INFO com.example.advancedspring.trace.threadlocal.ThreadLocalServiceTest - main start
15:09:42.293 [thread - A] INFO com.example.advancedspring.trace.threadlocal.code.ThreadLocalService - 저장 name=userA -> nameStore = null
15:09:42.397 [thread - B] INFO com.example.advancedspring.trace.threadlocal.code.ThreadLocalService - 저장 name=userB -> nameStore = null
15:09:43.301 [thread - A] INFO com.example.advancedspring.trace.threadlocal.code.ThreadLocalService - 조회 nameStore = userA
15:09:43.400 [thread - B] INFO com.example.advancedspring.trace.threadlocal.code.ThreadLocalService - 조회 nameStore = userB
15:09:44.402 [Test worker] INFO com.example.advancedspring.trace.threadlocal.ThreadLocalServiceTest - main exit
Share