Introduction
There are use cases where you want to start several threads and cancel all of them if they don't finish in time. Or maybe you want to start several virtual threads and only want them to run some predefined amount of time.
With structured concurrency setting deadlines and controlling the lifetime of threads is an easy task. In this short article, we will see how we can set a deadline on the virtual threads of the StructuredTaskScope.
Setting a deadline on StructuredTaskScope
StructuredTaskScope has two build-in shutdown policies ShutdownOnFailure and ShutdownOnSuccess. Both policies
have a method called joinUntil(Instant deadline)
that takes an Instant as parameter and is used as the deadline.
In the following example at line 7 the joinUntil method is called with Instant.ofEpochSecond(10)
as parameter. The code
will wait at line 7 till either the threads are done or 10 seconds have passed. This means that the two threads have 10
seconds to perform their task. If the two threads run for more than 10 seconds their shutdown method will be invoked.
|
|
Further reading
More about virtual threads in Java: