Virtual threads · Topic 3 of 4
One virtual thread per task
Definition​
The usual way to use virtual threads is an executor that starts a new virtual thread for every task. Because they are cheap you do not pool them. Using the executor in try-with-resources waits for all tasks before continuing.
Example code​
Fetching 5 values at the same time with plain blocking code
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
class Demo {
static String fetch(int id) throws InterruptedException {
Thread.sleep(200); // blocking is cheap on a virtual thread
return "item-" + id;
}
public static void main(String[] args) throws Exception {
List<Future<String>> futures = new ArrayList<>();
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
for (int id = 1; id <= 5; id++) {
int copy = id;
futures.add(executor.submit(() -> fetch(copy)));
}
} // waits here until all 5 are done
for (Future<String> future : futures) System.out.println(future.get());
}
}
// Output:
// item-1
// item-2
// item-3
// item-4
// item-5
Finished this page? Track your progress (saved only in your browser).