How to ask CompletableFuture use non-daemon threads?

馋奶兔 提交于 2020-01-29 08:43:06

问题


I have wrote following code:

 System.out.println("Main thread:" + Thread.currentThread().getId());
 CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
     try {
         System.out.println("Before sleep thread:" + Thread.currentThread().getId(), + " isDaemon:" + Thread.currentThread().isDaemon());
          Thread.sleep(100);
          System.out.println("After sleep");
      } catch (InterruptedException e) {
          e.printStackTrace();
      }
  });
  future.whenComplete((r, e) -> System.out.println("whenCompleted thread:" + Thread.currentThread().getId()));

and this one prints:

Main thread:1
Before sleep thread:11 isDaemon:true

and finishes.

How can I change this behaviour?

P.S. I don't see anything related in runAsync java doc


回答1:


The javadoc for runAsync() says:

Returns a new CompletableFuture that is asynchronously completed by a task running in the ForkJoinPool.commonPool() after it runs the given action.

There is another version of runAsync() where you can pass an ExecutorService.

Thus: when the default commonPool() doesn't do what you want - then create your own ExecutorService instead.




回答2:


Add this line:

ForkJoinPool.commonPool().awaitTermination(5, TimeUnit.SECONDS);

to the main method after running your future. I'll block until all tasks in the pool have been completed.

Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first.



来源:https://stackoverflow.com/questions/46032904/how-to-ask-completablefuture-use-non-daemon-threads

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!