Giovanni Bricconi

My site on WordPress.com

jep/428 Java Structured Concurrency

leave a comment »

Well it is a lot of time I do not develop concurrent code in Java, but reading this JEP has been really nice and I hope it will find its way to an official feature.

An example is given, where one task spawns 2 parallel threads. If everything goes fine we are all happy, but if one of the threads gets interrupted it is easy to have some leaks. For instance if one of the sub-threads fails, also the second thread should be killed and the parent thread interrupted.

Manually coding this seems complicated, and difficult to test. The StructuredTaskScope they propose seems good to solve many problem, event though the syntax is a bit cumbersome

Response handle() throws ExecutionException, InterruptedException {
    try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
        Future<String>  user  = scope.fork(() -> findUser()); 
        Future<Integer> order = scope.fork(() -> fetchOrder());

        scope.join();          // Join both forks
        scope.throwIfFailed(); // ... and propagate errors

        // Here, both forks have succeeded, so compose their results
        return new Response(user.resultNow(), order.resultNow());
    }
}

Also they propose to modify the thread dumps to make evident the problems caused by subtask failures.

I hope you will enjoy reading JEP 428: Structured Concurrency (Incubator)

Written by Giovanni

June 3, 2022 at 1:21 pm

Posted in Varie

Leave a comment