Contents

Structured Concurrency Deadline

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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
static String d() throws ExecutionException, InterruptedException, TimeoutException {
    try (var scope = new StructuredTaskScope.ShutdownOnSuccess<String>()) {
        Future<String> futureA = scope.fork(() -> getStringFromResourceA());
        Future<String> futureB = scope.fork(() -> getStringFromResourceB());

        // Wait till threads are done or deadline has passed
        scope.joinUntil(Instant.ofEpochSecond(10));

        return "result: " + futureA.resultNow() + " " + futureB.resultNow();
    }
}

Further reading

More about virtual threads in Java:

Have a question or idea?

Thank you for reading my post. Have any questions about this topic or an idea for a new topic? Please reach out to me on Twitter or send me an email.

If you want to read more about Java when I write about it – you can follow me on Twitter.