I found there are two ways (submit and execute) to add a Runnable into a thread pool, what is the difference?
Asked
Active
Viewed 4.5k times
3 Answers
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
-
2Also 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).
путин некультурная свинья
- 90,759
- 19
- 173
- 265
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.
Rahul Baradia
- 11,749
- 16
- 74
- 121
AdamH
- 1,368
- 9
- 10