views:

52

answers:

3

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

+3  A: 

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
`Future` also allows you to get exceptions thrown by `Runnable`.
axtavt
@axtavt: True, guess I should mention that too.
ColinD
+1  A: 

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

http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/ThreadPoolExecutor.html#execute(java.lang.Runnable)

http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/AbstractExecutorService.html#submit(java.util.concurrent.Callable)

AdamH
+1  A: 

The submit(...) method is executor framework extension introduced in ExecutorService interface.
It's main difference from execute(Runnable) is that it can accept Callable<V> (whereas execute() accepts only Runnable) and returns instance of Future<V>, which you can use later in caller to retrieve result of asynchronous computation (potentially blocking until computation is completed).

Victor Sorokin