From the course: Top Features of Java 21

Unlock this course with a free trial

Join today to access over 25,300 courses taught by industry experts.

Using virtual threads

Using virtual threads - Java Tutorial

From the course: Top Features of Java 21

Using virtual threads

- [Instructor] Let's see how we can use virtual threads to improve throughput in a real example. In this example, I have a class called Main with a main method. And in here, I have some codes that uses platform threads to run some code concurrently. So the first thing this code does is it creates an executive service using a method called newFixedThreadPool, and I'm passing in the number one. This means that I will use one thread to execute the code. Then I'm creating an IntStream from 0 to 99,999. So basically just some really big number. And for each of these numbers, I'm calling the submit method on the executor service and telling the thread to sleep for one second. In real life, there might be some more interesting operation that takes one second to complete. For example, doing some writes to a database. But to keep it simple, I'm just telling it to sleep for a second. Then I'm printing out the integer i so we can…

Contents