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:

Join the discussion: follow me on Twitter and share your thoughts

This post is just the beginning. If you're interested in learning more, be sure to follow me on Twitter . And if you have any questions or ideas, don't hesitate to reach out via Twitter or send me an email. I'm always happy to connect and continue the conversation.