Contents

Future with Virtual threads

Written by: David Vlijmincx

Introduction

We are gonna look at how to use virtual threads with a future. Doing this requires only a couple lines of code. A future makes it is easy to return a value from a (virtual) thread.

Future with a virtual thread

Creating a future from a virtual thread is done by using the newVirtualThreadPerTaskExecutor. Since Java 21 the ExecutorService now implements the autocloseable interface which means that we can use it with the try-with-resource statement.

1
2
3
4
5
6
7
8
9
try (ExecutorService vte = Executors.newVirtualThreadPerTaskExecutor()) {
    Future<String> myFuture = vte.submit(() ->
            {
                Thread.sleep(1000);
                return "Hello, World!";
            }
    );

}

In the previous example, you can see on line 2 how the future is created. The virtual thread will sleep for a second and return a string for the future to get.

Consuming a future from a virtual thread

Getting a value from a future is as simple as calling .get(). This will block the thread calling the get() method till the future is done. You can see how to do this in the following example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
try (ExecutorService vte = Executors.newVirtualThreadPerTaskExecutor()) {
    Future<String> myFuture = vte.submit(() ->
            {
                Thread.sleep(1000);
                return "Hello, World!";
            }
    );

    String result = myFuture.get();

    System.out.println("result = " + result);

} catch (ExecutionException | InterruptedException e) {
    throw new RuntimeException(e);
}

In the previous example, you can see how to consume a value from a future. On line 9 the value is taken from the future and later printed to the console.

Conclusion

You learned how to get a future from a virtual thread and how to get a value from a future.