34

I found there are two ways (submit and execute) to add a Runnable into a thread pool, what is the difference?

virsir
  • 14,799
  • 23
  • 73
  • 108

3 Answers3

38

The difference is that execute doesn't return a Future, so you can't wait for the completion of the Runnable and get any exception it throws using that.

ColinD
  • 106,341
  • 29
  • 198
  • 201
  • 4
    `Future` also allows you to get exceptions thrown by `Runnable`. – axtavt Oct 25 '10 at 15:36
  • @axtavt: True, guess I should mention that too. – ColinD Oct 25 '10 at 15:40
  • 2
    Also good to note that as a consequence of the exception being part of the Future's return value, the thread's uncaught exception handler will never be called for `submit`, whereas it will for `execute`. – Dennie Apr 03 '18 at 10:08
16

The submit(...) method is an executor framework extension introduced in ExecutorService interface.

Its main difference from execute(Runnable) is that submit(...) can accept a Callable<V> (whereas execute() accepts only Runnable) and returns an instance of Future<V>, which you can use later in the caller to retrieve the result asynchronously (potentially blocking until the computation performed by the Callable is completed).

Victor Sorokin
  • 11,695
  • 1
  • 33
  • 49
1

Submit appears to be a more generic form of execute. In particular, submit returns a Future object that represents the result of the computation.

ThreadPoolExecutor-1

ThreadPoolExecutor -2

Rahul Baradia
  • 11,749
  • 16
  • 74
  • 121
AdamH
  • 1,368
  • 9
  • 10