Running multiple tasks and processing all the results

The Executor framework allows you to execute concurrent tasks without worrying about thread creation and execution. It provides you with the Future class, which you can use to control the status and get the results of any task executed in an executor.

When you want to wait for the finalization of a task, you can use the following two methods:

  • The isDone() method of the Future interface returns true if the task has finished its execution
  • The awaitTermination() method of the ThreadPoolExecutor class puts the thread to sleep until all the tasks have finished their execution after a call to the shutdown() method

These two methods have some drawbacks. With the first one, you can only control the completion of a task. With the second one, you have to shut down the executor to wait for a thread; otherwise, the method's call is returned immediately.

The ThreadPoolExecutor class provides a method that allows you to send a list of tasks to the executor and wait for the finalization of all the tasks in the list. In this recipe, you will learn how to use this feature by implementing an example with 10 tasks executed and their results printed out when they have finished.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.19.75