Search code examples
javathreadpoolexecutorcallableblockingqueue

How does a ThreadPoolExecutor that is created using the constructor with BlockingQueue<Runnable> as an argument, enqueue Callables?


The constructor for ThreadPoolExecutor has the type argument for the BlockingQueue as Runnable.
Let's suppose I have a ThreadPoolExecutor declared like this

ThreadPoolExecutor customThreadPool = new ThreadPoolExecutor(numberOfAvailableProcessors,
                                numberOfAvailableProcessors, 2L,
                                TimeUnit.MILLISECONDS,
                                new LinkedBlockingQueue<>(),
                                Executors.defaultThreadFactory(),
                                new RejectedExecutionHandler() {
                                    @Override
                                    public void rejectedExecution(Runnable r, ThreadPoolExecutor threadPoolExecutor) {
                                        // Do something here to handle it
                                    }
                                });  

My question is that when is do something like:

customThreadPool.submit(new Callable<Integer>() {
                @Override
                public Integer call() throws Exception {
                    return Math.toIntExact(Thread.currentThread().getId());
                }
            })  

How does the ThreadPool handle this even though I have specified the type argument of the Queue to be Runnable?
How will this task be queued?


Solution

  • That's because it wraps your Callable task as a RunnableFuture before queueing or executing.

    This RunnableFuture implements Runnable interface (in addition to the Future).

    So all callables could be queued and executed without any issue.

    Have a look at AbstractExecutorService source for further info.