Since Java 21 we have virtual threads. But how can we take advantage of virtual thread wen we use ExecutorService or ScheduledExecutorService?
For an ExecutorService you can just use the factory method Executors.newVirtualThreadPerTaskExecutor() or if you want to give the virtual threads a name:
ThreadFactory threadFactory = Thread.ofVirtual().name("virtualThread").factory();
ExecutorService service = Executors.newThreadPerTaskExecutor(threadFactory);
For a ScheduledExecutorService you can use the following code:
ThreadFactory threadFactory = Thread.ofVirtual().name("virtualThread").factory();
ScheduledExecutorService service = Executors.newScheduledThreadPool(0, threadFactory);
Leave a Reply