Create ExecutorService and ListeningExecutorService

By | March 10, 2017
Share the joy
  •  
  •  
  •  
  •  
  •  
  •  

Executor is a interface, there is no way to create it.

Normally, there are 2 ways to create ExecutorService:

ExecutorService service = Executors.newFixedThreadPool(10);
ExecutorService service = Executors.newSingleThreadExecutor();

Normally, use decorator to create ListeningExecutorService by ExecutorService:

ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10));

Compared to Executor, ExecutorService has shutdown function.

ExecutorService returns Future, ListeningExecutorService returns ListenableFuture.

Compared to Future, ListenableFuture can attach a callback, which will be called when result is available. The callback and submit doesn’t has an order sequence.

public static void callBack() throws Exception{
    ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10));
    Callable<String> c = () -> {
        return "abcd";
    };
    ListenableFuture<String> future = service.submit(c);
    Runnable callBack = () -> {
        System.out.println("in callback: " + java.lang.Thread.activeCount());
    };
    future.addListener(callBack, service);
    System.out.println(future.get());
}

Above code will generate 2 threads. service generates 2 threads. One is called by service.submit, another is called by future.addListener(callBack, service). These 2 threads doesn’t has sequence order.