ExecutorService execute method in java

Prerna Gupta :

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.

Saptarshi Basu :

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)
  1. Idle threads will die if the total number of threads is more than corePoolSize
  2. If the number of tasks submitted are more than corePoolSize, new threads will be created until maximumPoolSize is reached
  3. 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 is ThreadPoolExecutor.CallerRunsPolicy, the caller thread will execute the task
  4. newFixedThreadPool is a specialized instance of ThreadPoolExecutor as given below. The corePoolSize and maximumPoolSize are same. The saturation policy is not provided - hence the default policy ThreadPoolExecutor.AbortPolicy is used.
return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=28773&siteId=1