ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Java Virtual Thread (10), @async 어노테이션
    프로그래밍/Java 2024. 6. 29. 10:51

    Controller.java

    @GetMapping("/async")
    public void async() {
        log.info("1) async. thread: {}", Thread.currentThread());
        virtualService.async();
        log.info("2) async. thread: {}", Thread.currentThread());
    }

     

     

     

    Service.java

    import lombok.extern.slf4j.Slf4j;
    import org.springframework.scheduling.annotation.Async;
    import org.springframework.stereotype.Service;
    
    @Service
    @Slf4j
    public class VirtualService {
    
        @Async("threadPoolTaskExecutor")
        public void async() {
            log.info("1) async. thread: {}", Thread.currentThread());
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            log.info("2) async. thread: {}", Thread.currentThread());
        }
    }

     

    @Async 어노테이션에서 Virtual Thread가 잘 동작하는지 확인해보자.

     

     

    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.scheduling.annotation.EnableAsync;
    
    @EnableAsync
    @SpringBootApplication
    public class VirtualthreadApplication {
    	public static void main(String[] args) {
    		SpringApplication.run(VirtualthreadApplication.class, args);
    	}
    }

     

     

    Spring에서 비동기로 제일 쉽게 하는 것이 @Async이다. 그리고 @Async 를 사용할 땐 @EnableAsync를 적어줘야 한다.

     

     

     

    위 코드를 실행해보면, 컨트롤러에서는 Tomcat handler-0 이라는 스레드가 virtual thread가 사용되었다. 그리고 서비스에서는 task1 이라고하는  virtual thread가 사용된 것을 알 수 있다. 

     

    즉, 컨트롤러에서는 tomcat handler-0, @async가 선언된 서비스에서는 task 1이라고 하는 virtual thread가 사용된 것이다. 원래는 thread pool 에 있는 것을 자동으로 사용했다면, 이제는 virtual thread가 적용되는 것이다.

     

     

    ...

     

     

    정리

     

    1) spring 에서 사용하는 @async 에도 virtual thread 가 적용된다.

    2) 컨트롤러에서는 tomcat handler-0 이라는 virtual thread 가 호출되며 @async가 선언된 구문에서는 task 1 이라는 virtual thread가 호출된다.

    3) 만약 virtual thread를 적용하지 않았다면 자동으로 thread pool을 사용했을 것이다.

Designed by Tistory.