简体   繁体   English

主线程在CompletableFuture完成之前退出

[英]Main thread exits before the completion of CompletableFuture

    CompletableFuture feature = CompletableFuture.supplyAsync (() ->       composeMethod ( )).
            thenAccept (s -> System.out.println ("wassup java" + s)).
            thenRun (() -> System.out.println (" imm immortal"));
    nonblockingmethod ( );

This is the CompletableFuture future example im working on 这是我正在进行的CompletableFuture未来示例

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";
    }

first i call compose method from supplyAsync , where i execute the method composeMethod , there is a three millisecond delay and then it will create a file and return a string as result . 首先我从supplyAsync调用compose方法,其中我执行方法composeMethod,有一个3毫秒的延迟然后它将创建一个文件并返回一个字符串作为结果。 after its completion i call thenRun method which just prints a method , After that there is a nonblockingmethod which runs from the main thread . 在完成后我调用thenRun方法,它只打印一个方法,之后有一个非阻塞方法从主线程运行。

the problem i face here is the main Thread finish executing the nonblockingmethod() and exits the process before the 3 millisecond delay while the subsequent operation from composeMethod. 我面临的问题是主线程完成执行nonblockingmethod()并在3毫秒延迟之前退出进程,而后续操作来自composeMethod。 is this teh expected behaviour or i have to block the main thread using get or join , or i miss anything 是这个预期的行为,或者我必须使用get或join来阻止主线程,或者我想念任何事情

Your task provided in the supplyAsync will execute in the ForkJoinPool#commonPool . supplyAsync提供的supplyAsync将在ForkJoinPool#commonPool执行。 And if you take a look on the thread in the common pool you can see that they are Deamon thread , that means JVM will not wait to Shutdown for that daemon thread to complete its execution when there is no active non-daemon thread .In your case, you have a sleep in composeMethod and in the meantime, main thread executes and completed its work, and JVM does not have any active non-daemon thread .So, JVM will go to shut down without waiting for your task to complete. 如果您查看common pool的线程,您可以看到它们是Deamon thread ,这意味着当没有active non-daemon thread时,JVM将不会等待该守护程序线程的Shutdown以完成其执行。例如,你在composeMethod中睡眠,同时主线程执行并完成其工作,而JVM does not have any active non-daemon thread 。因此,JVM将shut down而不等待你的任务完成。 If you run the below example you can confirm about the thread pool and type of thread. 如果运行以下示例,则可以确认线程池和线程类型。

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"));

Output: 输出:

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();

Output: 输出:

Thread : Thread[pool-1-thread-1,5,main]
Is Daemon : false
why  should i wait for you 
wassup java   resultdaa
 imm immortal

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM