bremen_matt
bremen_matt

Reputation: 7349

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.

Upvotes: 4

Views: 1585

Answers (2)

Max
Max

Reputation: 2136

In addition to the other answers, this quote from the Executor javadoc provides an example of an Executor implementation which runs the code in the calling thread,

However, the Executor interface does not strictly require that execution be asynchronous. In the simplest case, an executor can run the submitted task immediately in the caller's thread:

class DirectExecutor implements Executor {    
    public void execute(Runnable r) {
        r.run();    
    }  
}

More typically, tasks are executed in some thread other than the caller's thread. The executor below spawns a new thread for each task.

class ThreadPerTaskExecutor implements Executor {    
    public void execute(Runnable r) {
        new Thread(r).start();    
    }  
}

Upvotes: 2

assylias
assylias

Reputation: 328619

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.

Upvotes: 4

Related Questions