Skip to content

Interoperability with Structured Concurrency #272

@njr-11

Description

@njr-11

Structured Concurrency has been in incubation in Java 19 and 20 and might be part of a supported release of Java SE at some point, in which case the Concurrency specification should address how it pertains to Jakarta EE. Some of the information that follows might become out of date by the time structured concurrency actually goes in, so please check on the accuracy of it.

The main way of interacting with Structured Concurrency is StructuredTaskScope, which has a fork method that accepts a Callable task. There is no way provided for the Jakarta EE Concurrency specification to automatically tie into it.

There are some steps that users can take manually to leverage existing APIs from the Jakarta EE Concurrency specification to ensure that their tasks run with context.

At the most granular level, you can use the ContextService.contextualCallable method that we added in Jakarta EE 10 to pre-contextualize Callables that you supply to the fork method.

try (var scope = new StructuredTaskScope<Object>()) {
    Future<Long> future1 = scope.fork(contextService.contextualCallable(task1));
    Future<Long> future2 = scope.fork(contextService.contextualCallable(task2));
    scope.join();
    ...
}

There is also a constructor that you can use to designate a specific ThreadFactory to be used by the StructuredTaskScope. The ThreadFactory could be a ManagedThreadFactory,

try (var scope = new StructuredTaskScope<Object>("MyTaskScopeWithContext", managedThreadFactory)) {
    Future<Long> future1 = scope.fork(task1);
    Future<Long> future2 = scope.fork(task2);
    scope.join();
    ...
}

The above is what will be possible if we don't do anything new in the Jakarta EE Concurrency spec for this. There will be the above ways of contextualizing tasks, but no ways of constraining concurrency.

StructuredTaskScope can be extended with subclasses. It even provides a couple of built-in ones:
https://download.java.net/java/early_access/jdk20/docs/api/jdk.incubator.concurrent/jdk/incubator/concurrent/StructuredTaskScope.ShutdownOnFailure.html
https://download.java.net/java/early_access/jdk20/docs/api/jdk.incubator.concurrent/jdk/incubator/concurrent/StructuredTaskScope.ShutdownOnSuccess.html
The Jakarta EE Concurrency specification could do something with subclasses and maybe let you obtain StructuredTaskScopes from managed executors if we thought that would be useful. More investigation is needed.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions