Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ask CompletableFuture use non-daemon threads?

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

like image 678
gstackoverflow Avatar asked Sep 04 '17 08:09

gstackoverflow


1 Answers

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.

like image 63
GhostCat Avatar answered Sep 22 '22 12:09

GhostCat