|
| 1 | +package features_versions.nineteen_19.base; |
| 2 | + |
| 3 | +import java.time.Duration; |
| 4 | +import java.util.concurrent.Executors; |
| 5 | +import java.util.stream.IntStream; |
| 6 | + |
| 7 | +/** |
| 8 | + * JEP 425: Virtual Threads (Preview) |
| 9 | + * |
| 10 | + * This JEP introduces virtual threads, a lightweight implementation of threads provided by the JDK instead of the OS. |
| 11 | + * The number of virtual threads can be much larger than the number of OS threads. These virtual threads help increase |
| 12 | + * the throughput of the concurrent applications. |
| 13 | + */ |
| 14 | +public class VirtualThreads { |
| 15 | + |
| 16 | + public static void main(String[] args) { |
| 17 | + usingVirtualThreads(); |
| 18 | + usingNewFixedThreadPool(); |
| 19 | + } |
| 20 | + |
| 21 | + public static void usingVirtualThreads() { |
| 22 | + |
| 23 | + long startTime = System.currentTimeMillis(); |
| 24 | + System.out.println(STR."Using virtual threads start time: \{startTime}"); |
| 25 | + |
| 26 | + // finish within 1 second |
| 27 | + try (var executor = Executors.newVirtualThreadPerTaskExecutor()) { |
| 28 | + IntStream.range(0, 10_000).forEach(i -> { |
| 29 | + executor.submit(() -> { |
| 30 | + Thread.sleep(Duration.ofSeconds(1)); |
| 31 | + return i; |
| 32 | + }); |
| 33 | + }); |
| 34 | + } |
| 35 | + |
| 36 | + long endTime = System.currentTimeMillis(); |
| 37 | + System.out.println(STR."Using virtual threads end time: \{endTime}"); |
| 38 | + System.out.println(STR."Using virtual threads duration: \{endTime - startTime}"); |
| 39 | + |
| 40 | + } |
| 41 | + |
| 42 | + /** |
| 43 | + * This method uses the newFixedThreadPool to execute the 10_000 tasks. |
| 44 | + * You probably need to manually stop the process because it takes a long time to finish. |
| 45 | + */ |
| 46 | + public static void usingNewFixedThreadPool() { |
| 47 | + |
| 48 | + long startTime = System.currentTimeMillis(); |
| 49 | + System.out.println(STR."Using newFixedThreadPool start time: \{startTime}"); |
| 50 | + |
| 51 | + // 10_000/20 = 500seconds, it takes 8 minutes and 33 seconds to finish it |
| 52 | + try (var executor = Executors.newFixedThreadPool(20)) { |
| 53 | + IntStream.range(0, 10_000).forEach(i -> { |
| 54 | + executor.submit(() -> { |
| 55 | + Thread.sleep(Duration.ofSeconds(1)); |
| 56 | + return i; |
| 57 | + }); |
| 58 | + }); |
| 59 | + } |
| 60 | + |
| 61 | + long endTime = System.currentTimeMillis(); |
| 62 | + System.out.println(STR."Using newFixedThreadPool end time: \{endTime}"); |
| 63 | + System.out.println(STR."Using newFixedThreadPool duration: \{endTime - startTime}"); |
| 64 | + |
| 65 | + } |
| 66 | + |
| 67 | + |
| 68 | + |
| 69 | + |
| 70 | + |
| 71 | + |
| 72 | + |
| 73 | + |
| 74 | + |
| 75 | + |
| 76 | + |
| 77 | + |
| 78 | + |
| 79 | + |
| 80 | + |
| 81 | + |
| 82 | +} |
0 commit comments