CompletableFuture feature = CompletableFuture.supplyAsync (() -> composeMethod ( )).
thenAccept (s -> System.out.println ("wassup java" + s)).
thenRun (() -> System.out.println (" imm immortal"));
nonblockingmethod ( );
这是我正在处理的 CompletableFuture future 示例
private static void nonblockingmethod() {
System.out.println ("why should i wait for you ");
}
private static String composeMethod() {
try {
TimeUnit.MILLISECONDS.sleep (3);
File file = Paths.get ("/Users/solo/solo1.txt").toFile ( );
if (!file.exists ( )) {
file.createNewFile ( );
}
} catch (Exception e) {
}
return " resultdaa";
}
首先,我从 supplyAsync 调用 compose 方法,在其中执行 composeMethod 方法,有一个三毫秒的延迟,然后它将创建一个文件并返回一个字符串作为结果。完成后我调用 thenRun 方法,它只打印一个方法,之后有一个从主线程运行的非阻塞方法。
我在这里面临的问题是主线程完成执行 nonblockingmethod() 并在 3 毫秒延迟之前退出进程,而后续操作来自 composeMethod。这是预期的行为还是我必须使用 get 或 join 阻塞主线程,否则我会错过任何东西
supplyAsync
中提供的任务将在 ForkJoinPool#commonPool
中执行。如果你看一下 common pool
中的线程,你会发现它们是 Deamon thread
,这意味着 JVM 不会等待当没有 active non-daemon thread
时关闭该守护线程以完成其执行。在您的情况下,您在 composeMethod
中 hibernate ,与此同时,主线程执行并完成其工作,JVM 没有任何 Activity 的非守护线程
。因此,JVM 将进入关闭
,而不等待您的任务完成。如果运行以下示例,您可以确认线程池和线程类型。
CompletableFuture feature = CompletableFuture.supplyAsync(() -> {
System.out.println("Thread : " + Thread.currentThread());
System.out.println("Is Daemon : " + Thread.currentThread().isDaemon());
return composeMethod();
}).thenAccept(s -> System.out.println("wassup java" + s)).thenRun(() -> System.out.println(" imm immortal"));
输出:
Thread : Thread[ForkJoinPool.commonPool-worker-1,5,main] // This line may be bit different but it indicates that your task is executing on Common pool
Is Daemon : true
why should i wait for you
To resolve the issue you can pass your own executor like below:
ExecutorService executorService = Executors.newFixedThreadPool(8);
CompletableFuture feature = CompletableFuture.supplyAsync(() -> {
System.out.println("Thread : " + Thread.currentThread());
System.out.println("Is Daemon : " + Thread.currentThread().isDaemon());
return composeMethod();
}, executorService).thenAccept(s -> System.out.println("wassup java" + s))
.thenRun(() -> System.out.println(" imm immortal"));
executorService.shutdown();
nonblockingmethod();
输出:
Thread : Thread[pool-1-thread-1,5,main]
Is Daemon : false
why should i wait for you
wassup java resultdaa
imm immortal