What is the difference between ExecutorService.submit and ExecutorService.execute in this code in Java?

前端 未结 8 1339
你的背包
你的背包 2021-01-30 00:05

I am learning to use ExectorService to pool threads and send out tasks. I have a simple program below

import java.util.concurrent.Execu         


        
8条回答
  •  滥情空心
    2021-01-30 00:30

    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()

    1. Wrap your Callable or Runnable code in try{} catch{} block

      OR

    2. Keep future.get() call in try{} catch{} block

      OR

    3. 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

提交回复
热议问题