jdk 21中的虚拟线程已经推出好一段时间了,确实很轻量,先来一段示例:
假如有一段提交订单的业务代码:
1 public void submitOrder(Integer orderId) { 2 sleep(1000); 3 System.out.println("order:" + orderId + " is submitted"); 4 }
这里我们用sleep来模拟,每提交1个订单,大致耗时1秒。
如果有10个订单一起下单,顺序执行的话,至少10秒,很容易想到用多线程:
1 @Test 2 public void submitOrder1() { 3 ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("submitOrder-pool-%d").build(); 4 ExecutorService submitOrderPool = new ThreadPoolExecutor(4, 16, 300L, TimeUnit.SECONDS, 5 new LinkedBlockingQueue<>(128), threadFactory, new ThreadPoolExecutor.DiscardOldestPolicy()); 6 CompletableFuture<Void>[] futures = new CompletableFuture[10]; 7 StopWatch watch = new StopWatch(); 8 watch.start(); 9 //下10个订单 10 for (int i = 0; i < 10; i++) { 11 final int orderId = i; 12 CompletableFuture<Void> future = CompletableFuture.runAsync(() -> submitOrder(orderId), submitOrderPool); 13 futures[i] = future; 14 } 15 CompletableFuture.allOf(futures).join(); 16 watch.stop(); 17 System.out.println("Time: " + watch.getTime()); 18 }
这里我们使用了传统的线程池,核心线程数是4,小于10,所以会内部排队,最终执行效果大致如下:
order:0 is submitted order:3 is submitted order:1 is submitted order:2 is submitted order:4 is submitted order:6 is submitted order:7 is submitted order:5 is submitted order:8 is submitted order:9 is submitted Time: 3035
明显快多了,但是占用了4个传统的java线程。
我们改用虚拟线程来改写:
1 @Test 2 public void submitOrder2() { 3 CompletableFuture<Void>[] futures = new CompletableFuture[10]; 4 StopWatch watch = new StopWatch(); 5 watch.start(); 6 //下10个订单(这里使用虚拟线程) 7 try (ExecutorService service = Executors.newVirtualThreadPerTaskExecutor()) { 8 for (int i = 0; i < 10; i++) { 9 final int orderId = i; 10 CompletableFuture<Void> future = CompletableFuture.runAsync(() -> submitOrder(orderId), service); 11 futures[i] = future; 12 } 13 CompletableFuture.allOf(futures).join(); 14 } 15 watch.stop(); 16 System.out.println("Time: " + watch.getTime()); 17 }
参考文档:
https://blog.moyucoding.com/jvm/2023/09/23/ultimate-guide-to-java-virtual-thread
https://docs.oracle.com/en/java/javase/21/core/virtual-threads.html#GUID-DC4306FC-D6C1-4BCC-AECE-48C32C1A8DAA