According to Runnable execute
method in Executor
, corresponding JAVA doc mentions that it:
Executes the given command at some time in the future. The command may execute in a new thread, in a pooled thread, or in the calling thread, at the discretion of the {@code Executor} implementation.
My doubt is, for example if we create executor service as
ExecutorService executor = Executors.newFixedThreadPool(5);
and create a Runnable
task and run it by the above execute
method as:
Runnable testRunnableTask = () -> {
Runnable testRunnableTask = () -> {
System.out.println("my tested function");
}
};
executor.execute(testRunnableTask);
Then this testRunnableTask
should be executed by one of the threads that we have initialized through our fixed thread pool. But as per JAVA doc it can be executed by new thread or thread pool or calling thread.
If my understanding is correct of JAVA doc, then my doubt is why execute
method doesn't always use one of the threads from the pool like other methods of ExecutorService
like submit
.
submit
will submit a task for execution by execute
. In other words, submit
internally calls execute
to execute the task.
How execute
will execute the task depends on the configuration or constructor you use for ThreadPoolExecutor
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler)
- Idle threads will die if the total number of threads is more than
corePoolSize
- If the number of tasks submitted are more than
corePoolSize
, new threads will be created untilmaximumPoolSize
is reached handler
implementation gives a saturation policy that determines what wil happen when all the threads are executing tasks and the bounded blocking queue is also full. If the handler implementation passed isThreadPoolExecutor.CallerRunsPolicy
, the caller thread will execute the tasknewFixedThreadPool
is a specialized instance ofThreadPoolExecutor
as given below. ThecorePoolSize
andmaximumPoolSize
are same. The saturation policy is not provided - hence the default policyThreadPoolExecutor.AbortPolicy
is used.
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());