Structured in JDK 21 will bring a leap forward in development programming

Recently, JEP 453, Structured Concurrency (Preview), has moved from the Targeted state to the Integrated state in JDK 21. This initial preview feature is derived from an incubating API that incorporates improvements based on the previous two rounds of incubation, JEP 428 delivered in JDK 19, Structured Concurrency (incubating) and JEP 437 delivered in JDK 20 , Structured Concurrency (second round of incubation). In the current proposal, the only notable change is that the StructuredTaskScope::fork(…) method returns a [ Subtask ] instead of a Future .

Structured Concurrency in JDK 21 is committed to introducing structured concurrency APIs to simplify concurrent programming. This approach treats groups of related tasks running in different threads as a unit of work, which simplifies error handling and cancellation, improves reliability, and enhances observability. Let's look at an example:

Response handle() throws ExecutionException, InterruptedException {
     try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
          Supplier<String>  user  = scope.fork(() ->  findUser());
          Supplier<Integer> order = scope.fork(() ->  fetchOrder());
          scope.join()            // Join both subtasks
                .throwIfFailed();  // ... and propagate errors
          // Here, both subtasks have succeeded, so compose their results
          return new Response(user.get(), order.get());
    }
    //...
}

This code creates a new StructuredTaskScope and uses it to create two branching subtasks, one of which executes findUser() and the other executes fetchOrder(). When both subtasks complete, it creates a new Response with the results of both subtasks.

Structured Concurrency is a preview API and is disabled by default. To use the StructuredTaskScope API, developers must compile the code with the preview API enabled, as shown in the following command:

javac --release 21 --enable-preview Main.java

Running the program also requires the same flags, as follows:

java --enable-preview Main

However, we can use the source code launcher to run it directly. In this case, the command line looks like this:

java --source 21 --enable-preview Main.java

However, it is also possible to use the jshell solution, but the preview feature still needs to be enabled. The command is as follows:

 jshell --enable-preview

In practice, when using StructuredTaskScope, in most cases, you will not use the StructuredTaskScope class directly, but use one of the two subclasses, both of which implement the shutdown strategy. These two subclasses, ShutdownOnFailure and ShutdownOnSuccess, respectively support the mode of closing the scope when the first subtask fails or succeeds.

Structured concurrency treats related tasks running in different threads as a unit of work. This approach simplifies error handling and cancellation, improves reliability, and enhances observability. Developers Ron Pressler , an advisory member of Oracle's technical staff and technical lead for OpenJDK's Loom project, and Alan Bateman , an engineer in Oracle's Java Platform group, intend to eliminate common risks associated with concurrent programming, such as thread leaks and Eliminate delays and enhance the observability of concurrent code.

This new feature is not intended to replace any of the concurrent constructs in the java.util.concurrent package, such as ExecutorService and Future. Nor is it intended to define a well-defined structured concurrency API for the Java platform, or a means of sharing data flow between threads. Current concurrent programming models, such as the ExecutorService API, introduce complexity and risk due to their unrestricted concurrency model. These models do not enforce or track relationships between tasks and subtasks, making concurrent task management and observability challenging.

Structured concurrency proposes that the task structure should reflect the code structure. In single-threaded code, execution always enforces a hierarchy of tasks and subtasks, and the lifetime of each subtask relative to other subtasks is governed by the syntactic block structure of the code.

The new StructuredTaskScope provides a simpler and safer alternative to ExecutorService. This API encapsulates a set of related tasks that should be completed together, and the failure of any subtask will cause the cancellation of the remaining subtasks.

For more details on these changes, including code examples and a full discussion of the motivation behind this feature, see OpenJDK 's website. This new API is an important step towards making concurrent programming easier, more reliable, and more observable. It is expected to be especially beneficial for building maintainable, reliable, and observable server applications.

Original link: https://www.infoq.com/news/2023/06/structured-concurrency-jdk-21/

Guess you like

Origin blog.csdn.net/xiangzhihong8/article/details/131381487