如何使用结构化并发运行 JDK 19?

Eri*_*luk 11 java project-loom java-19

我已对此进行了编辑,以使原始帖子的内容保持最新。

我想尝试JEP 428:结构化并发(孵化器)中定义的新Project Loom功能

我的 pom.xml 中有

<properties>
  <maven.compiler.executable>${env.JAVA_HOME}/bin/javac</maven.compiler.executable>
  <maven.compiler.source>19</maven.compiler.source>
  <maven.compiler.target>19</maven.compiler.target>
</properties>

. . .

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-compiler-plugin</artifactId>
  <version>3.10.1</version>
  <configuration>
    <compilerArgs>
      <arg>--add-modules=jdk.incubator.concurrent</arg>
      <arg>--enable-preview</arg>
    </compilerArgs>
  </configuration>
</plugin>
Run Code Online (Sandbox Code Playgroud)

其中JAVA_HOME指向 JDK 19,但是当我尝试通过构建时,mvn compile我得到

[ERROR] C:\Users\ERIC\Documents\git\loom-lab\laboratory\src\main\java\net\kolotyluk\loom\Structured.java:3:20:  error: package jdk.incubator.concurrent is not visible
[ERROR] C:\Users\ERIC\Documents\git\loom-lab\laboratory\src\main\java\net\kolotyluk\loom\Structures.java:3:20:  error: package jdk.incubator.concurrent is not visible
. . .
Run Code Online (Sandbox Code Playgroud)

很多人在这方面帮助了我,显然他们可以让它发挥作用,但由于某种原因,我无法开始mvn compile工作。

不过,我可以让代码在 IntelliJ 下编译和运行。当我可以让 IntelliJ 编译时,我从来没有无法让 Maven 编译。通常,情况恰恰相反。

Bas*_*que 5

module-info.java文件

我不理解所有的活动部分,但我确实成功地访问了新的Project Loom功能、虚拟线程结构化并发,并分别在 Java 19 中预览孵化

这是我的main方法。

record Event( UUID id , Instant when , Integer reading ) {}

try ( var scope = new StructuredTaskScope.ShutdownOnFailure() )
{
    Future < UUID > futureId = scope.fork( ( ) -> UUID.randomUUID() );
    Future < Instant > futureWhen = scope.fork( ( ) -> Instant.now() );
    Future < Integer > futureReading = scope.fork( ( ) -> ThreadLocalRandom.current().nextInt( 1 , 10 ) );

    scope.join();           // Join both forks
    scope.throwIfFailed();  // ... and propagate errors
    Event event = new Event( futureId.get() , futureWhen.get() , futureReading.get() );
    System.out.println( event );
}
catch ( InterruptedException e )
{
    throw new RuntimeException( e );
}
catch ( ExecutionException e )
{
    throw new RuntimeException( e );
}
Run Code Online (Sandbox Code Playgroud)

该代码使用这些导入:

import java.time.Instant;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadLocalRandom;
Run Code Online (Sandbox Code Playgroud)

运行时:

事件[id=de316aca-10b1-41ed-bfc6-732c4e184566,时间=2022-08-07T03:04:48.207650Z,读数=9]

module-info.java在包层次结构之外添加了一个文件,位于src/main/java.

module LoomEx {
    requires jdk.incubator.concurrent;
}
Run Code Online (Sandbox Code Playgroud)

和我的POM我从列出的Apache Maven QuickStart原型开始。然后我将所有版本号更新到最新。

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns = "http://maven.apache.org/POM/4.0.0"
         xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>work.basil.example</groupId>
    <artifactId>Loom</artifactId>
    <version>1.0-SNAPSHOT</version>

    <name>Loom</name>
    <!-- FIXME change it to the project's website -->
    <url>http://www.example.com</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.release>19</maven.compiler.release>
    </properties>

    <dependencies>

        <!-- https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter -->
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter</artifactId>
            <version>5.9.0</version>
            <scope>test</scope>
        </dependency>


    </dependencies>

    <build>
        <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (maybe moved to parent pom) -->
            <plugins>
                <!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
                <plugin>
                    <artifactId>maven-clean-plugin</artifactId>
                    <version>3.2.0</version>
                </plugin>
                <!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
                <plugin>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>3.3.0</version>
                </plugin>
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.10.1</version>
                    <configuration>
                        <!--<compilerVersion>19</compilerVersion>-->
                        <release>19</release>
                        <!--<compilerArgs>&#45;&#45;source 19</compilerArgs>-->
                        <compilerArgs>--enable-preview</compilerArgs>
                        <!--<compilerArgs>&#45;&#45;add-modules jdk.incubator.concurrent</compilerArgs>-->
                    </configuration>
                </plugin>
                <plugin>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>3.0.0-M7</version>
                </plugin>
                <plugin>
                    <artifactId>maven-jar-plugin</artifactId>
                    <version>3.2.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-install-plugin</artifactId>
                    <version>3.0.1</version>
                </plugin>
                <plugin>
                    <artifactId>maven-deploy-plugin</artifactId>
                    <version>3.0.0</version>
                </plugin>
                <!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
                <plugin>
                    <artifactId>maven-site-plugin</artifactId>
                    <version>4.0.0-M3</version>
                </plugin>
                <plugin>
                    <artifactId>maven-project-info-reports-plugin</artifactId>
                    <version>3.4.0</version>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>
Run Code Online (Sandbox Code Playgroud)

我尝试使用从诸如thisthisthis 等页面获取的各种 Maven POM 元素,以及来自JEP 11: Incubator ModulesJEP 428: Structured Concurrency (Incubator) 的提示,希望不需要该module-info.java文件。但我无法让它发挥作用。添加模块信息文件是我成功的唯一途径。

当然,我必须设置 IntelliJ 埋藏在各个不同位置深处的常见多个奇怪设置,以指定 Java 19 的使用。有关这些麻烦设置的说明,请参阅其他 Stack Overflow 问题。(让我抓狂。绝对是 IntelliJ 中最烦人的问题/缺陷。为什么 IntelliJ 不能从 Maven POM 或 Gradle 设置中读取 Java 版本并完成它?)


Sla*_*law 5

我设法让它与 Maven 一起工作,而不需要module-info.java文件。我的 POM 和你的 POM 之间的主要区别似乎是我设置编译器参数的方式。而不是你拥有的:

<configuration>
  <compilerArgs>--source 19</compilerArgs>
  <compilerArgs>--enable-preview</compilerArgs>
  <compilerArgs>--add-modules jdk.incubator.concurrent</compilerArgs>
  <compilerVersion>19</compilerVersion>
  <source>19</source>
  <target>19</target>
</configuration>
Run Code Online (Sandbox Code Playgroud)

我有:

<configuration>
  <compilerArgs>
    <arg>--add-modules=jdk.incubator.concurrent</arg>
  </compilerArgs>
</configuration>
Run Code Online (Sandbox Code Playgroud)

注意我有<arg>嵌套在 中的元素<compilerArgs>。我也在争论=--add-modules,尽管我不知道这是否绝对必要。而且似乎--enable-preview只在运行时需要,而不是编译时。您拥有的其他参数我以不同的方式设置(例如,元素<properties>)。


例子

JAVA_HOME以下是设置为 JDK 19 安装的示例。

源/构建文件

应用程序.java:

package sample;

import jdk.incubator.concurrent.StructuredTaskScope;

public class App {
  public static void main( String[] args ) throws Exception {
    try (var scope = new StructuredTaskScope<Void>()) {
      scope.fork(() -> delayPrint(1000, "Hello,"));
      scope.fork(() -> delayPrint(2000, "World!"));
      scope.join();
    }
    System.out.println("Done!");
  }

  private static Void delayPrint(long delay, String message) throws Exception {
    Thread.sleep(delay);
    System.out.println(message);
    return null;
  }
}
Run Code Online (Sandbox Code Playgroud)

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.example</groupId>
  <artifactId>sample</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>sample</name>
  <url>http://maven.apache.org</url>
  
  <properties>
    <maven.compiler.source>19</maven.compiler.source>
    <maven.compiler.target>19</maven.compiler.target>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <build>

    <plugins>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.10.1</version>
        <configuration>
          <compilerArgs>
            <arg>--add-modules=jdk.incubator.concurrent</arg>
          </compilerArgs>
        </configuration>
      </plugin>

      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>exec-maven-plugin</artifactId>
        <version>3.1.0</version>
        <configuration>
          <executable>${java.home}/bin/java</executable>
          <arguments>
            <argument>--add-modules=jdk.incubator.concurrent</argument>
            <argument>--enable-preview</argument>
            <argument>--class-path</argument>
            <classpath/>
            <argument>sample.App</argument>
          </arguments>
        </configuration>
      </plugin>

    </plugins>
  </build>

</project>
Run Code Online (Sandbox Code Playgroud)

输出

编译:

> mvn compile

[INFO] Scanning for projects...
[INFO]
[INFO] -------------------------< com.example:sample >-------------------------
[INFO] Building sample 1.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ sample ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory C:\Users\***\Desktop\structured_concurrency\sample\src\main\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.10.1:compile (default-compile) @ sample ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 1 source file to C:\Users\***\Desktop\structured_concurrency\sample\target\classes
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  1.439 s
[INFO] Finished at: 2022-08-08T01:01:26-06:00
[INFO] ------------------------------------------------------------------------
Run Code Online (Sandbox Code Playgroud)

执行:

> mvn exec:exec

[INFO] Scanning for projects...
[INFO]
[INFO] -------------------------< com.example:sample >-------------------------
[INFO] Building sample 1.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- exec-maven-plugin:3.1.0:exec (default-cli) @ sample ---
WARNING: Using incubator modules: jdk.incubator.concurrent
Hello,
World!
Done!
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  2.610 s
[INFO] Finished at: 2022-08-08T01:02:42-06:00
[INFO] ------------------------------------------------------------------------
Run Code Online (Sandbox Code Playgroud)