35

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

virsir
  • 15,159
  • 25
  • 75
  • 109

3 Answers3

39

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
  • 108,630
  • 30
  • 201
  • 202
  • 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).

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
Victor Sorokin
  • 11,878
  • 2
  • 35
  • 51
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,802
  • 17
  • 73
  • 121
AdamH
  • 1,378
  • 9
  • 10