bremen_matt bremen_matt - 1 month ago 8
Java Question

ExecutorService might execute on calling thread?

If you read the documentation for Executor.execute, it says:


The command may execute in a new thread, in a pooled thread, or in the
calling thread
, at the discretion of the Executor implementation.


My understanding is that, by calling thread, they mean the thread that calls the
execute
command.

This has never happened in my experience, so my question is: Does this really ever happen?

Since the calling Thread controls the UI, I cannot allow additional work on the calling Thread. I am particularly concerned about whether this could happen when I construct the
ExecutorService
using the
Executors.newFixedThreadPool(threads)
method.

Answer

ExecutorService is an interface which defines a broad contract. If you look at implementations, say ThreadPoolExecutor for example, you will have more precise characteristics:

An ExecutorService that executes each submitted task using one of possibly several pooled threads, normally configured using Executors factory methods.

Note that the javadoc linked above details the fact that the ExecutorServices returned by the various Executors factory methods are ThreadPoolExecutors.

So to answer your question more directly: Executors.newFixedThreadPool(threads) will not execute tasks on the calling thread.

Comments