225. Tackling continuations
The concept that sits behind virtual threads is known as delimited continuations or simply continuations. This concept is used internally by the JVM in the following piece of code:
List<Thread> vtThreads = IntStream.range(0, 5)
.mapToObj(i -> Thread.ofVirtual().unstarted(() -> {
if (i == 0) {
logger.info(Thread.currentThread().toString());
}
try { Thread.sleep(1000); }
catch (InterruptedException ex) {}
if (i == 0) {
logger.info(Thread.currentThread().toString());
}
})).toList();
vtThreads.forEach(Thread::start);
vtThreads.forEach(thread -> {
try { thread.join(); } catch (InterruptedException ex) {}
});
In this code, we create and start five virtual threads but we only log information about one thread (thread #22 – of course, the id value may vary among executions). So, the output will be as follows:
VirtualThread[#22]/runnable@ForkJoinPool-1-worker-1
VirtualThread[#22...