티스토리 뷰

개발

java 21 virtual thread와 spring boot 3.2

달리는개발자 2023. 12. 6. 23:09

java 21에서 가장 주목해야되는 기능은 virtual thread인 것 같습니다.

우리가 만들었던 Thread는 Platform Thread이고 이 Thread는 OS Thread wrapper로 구현되어 있고 전체 수명동안 해당 OS Thread를 사용하게 됩니다.

아래 설명과 같이 Platform Thread는 비쌉니다.

보통 1MB 메모리를 사용한다고 들은 거 같은데 여긴 2MB로 가정하네요

그래서 전체 이용가능한 개수는 최대 OS thread 개수로 제한될 수 밖에 없고 large thread stack과 다른 리소스들을 가지고 있어서 많은 메모리를 사용하게 됩니다.

Virtual Thread는 경량 쓰레드여서 높은 처리량을 가지는 동시성 애플리케이션에 적합합니다.

경량 쓰레드라고 하는 이유는 Platform Thread와 OS Thread의 1:1 매핑이 아니며 많은 수의 Virtual thread를 소수의 OS Thread에 매핑합니다. 그리고 단일 HTTP Client 호출이나 단일 JDBC query 등과 같은 얕은 호출 스택을 갖고 있습니다.

동작은 OS Thread에서 구동되지만 blocking I/O 작업이 호출되면 자바 런타임은 해당 작업이 재개될 때까지 유예합니다.

아래 유튜브 영상이 잘 설명해주고 있네요

일단 중단된 virtual thread와 관련된 OS Thread는 다른 virtual thread의 작업을 수행할 수 있습니다.

Virtual thread는 blocked된 시간을 많이 보내는 작업에는 적합하지만 CPU를 오래 사용하는 작업에는 적합하지 않습니다.

 

처리량이 높은 애플리케이션에서 많은 동시성 작업들이 이루어지고 여기에서 대기하는 시간이 많아지는데 이런 곳에서 virtual thread를 사용합니다.

virtual thread를 사용한다고 platform thread보다 속도나 응답시간이 빨라지지 않습니다. virtual thread를 사용하는 이유는 처리량을 증가시키기 위함입니다.

virtual thread 생성 방법

Thread thread = Thread.ofVirtual().start(() -> System.out.println("Hello"));
thread.join();

보통은 위와 같은 방식은 쓰진 않죠

Executors 를 사용하면 편하고 관리하기 좋게 만들 수 있습니다.

try (ExecutorService myExecutor = Executors.newVirtualThreadPerTaskExecutor()) {
    Future<?> future = myExecutor.submit(() -> System.out.println("Running thread"));
    future.get();
    System.out.println("Task completed");
    // ...

 

 

 

 

Spring boot 3.2 부터 java 21 virtual thread를 지원합니다.

물론 java 21에서 구동되어야 되고 아래와 같은 설정이 필요합니다.

spring.threads.virtual.enabled=true

이렇게 설정이 되면 tomcat, jetty와 같은 servlet web server에 들어오는 요청이 모두 virtual thread로 동작하게 됩니다.

그외 task execution, task scheduling 등도 virtual thread를 사용하게 됩니다.

RabbitMQ listener나 kafka listener, Spring data redis의 ClusterCommandExecutor 에서도 virtual thread를 사용하게 됩니다.

 

webflux를 사용하면서도 virtual thread를 사용할 수 있습니다.

spring boot 3.2의 third-party dependency 중에 reactor 2023.0 이 있고 reactor-core 3.6.0 이 그 일부입니다.

여기에서 virtual thread를 지원하도록 설정할 수 있습니다.

이미 non-blocking, async이지만 결국 platform thread보다도 자원 효율적으로 사용할 수 있습니다.

아래와 같이 long-live 작업을 사용할 때는 executor-service 기반의 work를 사용하게 됩니다.

실무에서 이런 부분이 생각보다 많이 사용되게 됩니다.

....
.publishOn(Schedulers.boundedElastic())
...

....
.subscribeOn(Schedulers.boundedElastic())
...

아래와 같은 system property를 설정하면 이제 webflux boundedElastic에서 virtual thread를 사용하게 됩니다.

reactor.schedulers.defaultBoundedElasticOnVirtualThreads=true

 

참고

https://docs.oracle.com/en/java/javase/21/core/virtual-threads.html#GUID-2BCFC2DD-7D84-4B0C-9222-97F9C7C6C521

 

Core Libraries

Virtual threads are lightweight threads that reduce the effort of writing, maintaining, and debugging high-throughput concurrent applications.

docs.oracle.com

 

https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-3.2-Release-Notes

 

Spring Boot 3.2 Release Notes

Spring Boot. Contribute to spring-projects/spring-boot development by creating an account on GitHub.

github.com

https://github.com/reactor/reactor-core/releases

 

Releases · reactor/reactor-core

Non-Blocking Reactive Foundation for the JVM. Contribute to reactor/reactor-core development by creating an account on GitHub.

github.com

https://spring.io/blog/2023/10/31/what-new-is-coming-in-reactor-core-3-6-0#virtual-threads-support

 

What new is coming in reactor-core 3.6.0?

Reactor 3.6.0 is coming and going to be GA on November 14. This blogpost describes new features that are included in this upcoming release! Virtual Threads support Today, everyone talks about Java 21 and Project Loom. The Project Reactor team hears that an

spring.io

 

반응형
댓글
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함