Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between ExecutorService.submit and ExecutorService.execute in this code in Java?

I am learning to use ExectorService to pool threads and send out tasks. I have a simple program below

import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit;   class Processor implements Runnable {      private int id;      public Processor(int id) {         this.id = id;     }      public void run() {         System.out.println("Starting: " + id);          try {             Thread.sleep(5000);         } catch (InterruptedException e) {             System.out.println("sorry, being interupted, good bye!");             System.out.println("Interrupted " + Thread.currentThread().getName());             e.printStackTrace();         }          System.out.println("Completed: " + id);     } }   public class ExecutorExample {      public static void main(String[] args) {         Boolean isCompleted = false;          ExecutorService executor = Executors.newFixedThreadPool(2);          for (int i = 0; i < 5; i++) {             executor.execute(new Processor(i));         }          //executor does not accept any more tasks but the submitted tasks continue         executor.shutdown();          System.out.println("All tasks submitted.");          try {             //wait for the exectutor to terminate normally, which will return true             //if timeout happens, returns false, but this does NOT interrupt the threads             isCompleted = executor.awaitTermination(100, TimeUnit.SECONDS);             //this will interrupt thread it manages. catch the interrupted exception in the threads             //If not, threads will run forever and executor will never be able to shutdown.             executor.shutdownNow();         } catch (InterruptedException e) {         }          if (isCompleted) {             System.out.println("All tasks completed.");         } else {             System.out.println("Timeout " + Thread.currentThread().getName());         }     } } 

It does nothing fancy, but creates two threads and submits 5 tasks in total. After each thread completes its task, it takes the next one, In the code above, I use executor.submit. I also changed to executor.execute. But I do not see any difference in the output. In what way are the submit and execute methods different? This what the API says

Method submit extends base method Executor.execute(java.lang.Runnable) by creating and returning a Future that can be used to cancel execution and/or wait for completion. Methods invokeAny and invokeAll perform the most commonly useful forms of bulk execution, executing a collection of tasks and then waiting for at least one, or all, to complete. (Class ExecutorCompletionService can be used to write customized variants of these methods.)

But it's not clear to me as what it exactly means?

like image 651
brain storm Avatar asked Sep 10 '13 23:09

brain storm


People also ask

What does ExecutorService submit do?

The ExecutorService interface extends Executor by adding methods that help manage and control the execution of threads. It is defined in java. util. concurrent package.

What is the difference between ExecutorService and ScheduledExecutorService?

ScheduledExecutorService is an ExecutorService which can schedule tasks to run after a delay, or to execute repeatedly with a fixed interval of time in between each execution. Tasks are executed asynchronously by a worker thread, and not by the thread handing the task to the ScheduledExecutorService .

What is execute () in Java?

Java ThreadPoolExecutor execute() Method The execute() method of ThreadPoolExecutor class executes the given task sometime in the future. The task may execute in a new thread or an existing pooled thread.

What is an ExecutorService in Java?

ExecutorService is a JDK API that simplifies running tasks in asynchronous mode. Generally speaking, ExecutorService automatically provides a pool of threads and an API for assigning tasks to it.


1 Answers

As you see from the JavaDoc execute(Runnable) does not return anything.

However, submit(Callable<T>) returns a Future object which allows a way for you to programatically cancel the running thread later as well as get the T that is returned when the Callable completes. See JavaDoc of Future for more details

Future<?> future = executor.submit(longRunningJob); ... //long running job is taking too long future.cancel(true); 

Moreover, if future.get() == null and doesn't throw any exception then Runnable executed successfully

like image 180
dkatzel Avatar answered Sep 17 '22 04:09

dkatzel