I am learning to use ExectorService
to pool threads
and send out tasks. I have a simple program below
import java.util.concurrent.Execu
execute:
Use it for fire and forget calls
submit:
Use it to inspect the result of method call and take appropriate action on Future
objected returned by the call
Major difference: Exception
handling
submit()
hides un-handled Exception
in framework itself.
execute()
throws un-handled Exception
.
Solution for handling Exceptions with submit()
Wrap your Callable or Runnable code in try{} catch{} block
OR
Keep future.get() call in try{} catch{} block
OR
implement your own ThreadPoolExecutor
and override afterExecute
method
Regarding tour other queries on
invokeAll:
Executes the given tasks, returning a list of Futures holding their status and results when all complete or the timeout expires, whichever happens first.
invokeAny:
Executes the given tasks, returning the result of one that has completed successfully (i.e., without throwing an exception), if any do before the given timeout elapses.
Use invokeAll
if you want to wait for all submitted tasks to complete.
Use invokeAny
if you are looking for successful completion of one task out of N submitted tasks. In this case, tasks in progress will be cancelled if one of the tasks completes successfully.
Related post with code example:
Choose between ExecutorService's submit and ExecutorService's execute