Home > Back-end >  JAVA ThreadPoolExecutor workqueue with Callable
JAVA ThreadPoolExecutor workqueue with Callable

Time:02-08

Java ExecutorService.newFixedThreadPool() internally using a LinkedBlockingQueue<Runnable>() as below:

public static ExecutorService newFixedThreadPool(int nThreads) {
    return new ThreadPoolExecutor(nThreads, nThreads,
                                  0L, TimeUnit.MILLISECONDS,
                                  new LinkedBlockingQueue<Runnable>());
}

I am wondering when I call ExecutorService.submit(Callable<?>) with callable, how it is pushed into workQueue. As per docs, only Runnable are pushed to workQueue, then what happens to Callable when all threads are busy. Where these are kept for later processing.

As per docs

workQueue - the queue to use for holding tasks before they are executed. This queue will hold only the Runnable tasks submitted by the execute method.

CodePudding user response:

Callable is packaged as a FutureTask, which implements both Runnable and Future. Therefore, the FutureTask can also be executed or pushed to the queue. The FutureTask holds the Callable object. When the FutureTask is running, the Callable object is called and the future-related attributes are set. In fact, when a runnable is submitted, it is first packaged as a Callable and then packaged as a FutureTask.

CodePudding user response:

I believe that the callable is wrapped in a runnable when it is enqueued. Callables are definitely enqueue the same as runnables when all the workers are busy.

  •  Tags:  
  • Related