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
now implements the
autocloseable interface which means that we can use it with the try-with-resource statement.
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:
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.
You learned how to get a future from a virtual thread and how to get a value from a future.