There's more...

The Executors class provides other methods to create ThreadPoolExecutor:

  • newCachedThreadPool(): This method returns an ExecutorService object, so it's been cast to ThreadPoolExecutor to have access to all its methods. The cached thread pool you created creates new threads, if needed, to execute new tasks. Plus, it reuses the existing ones if they have finished the execution of the tasks they were running.
  • newSingleThreadExecutor(): This is an extreme case of a fixed-size thread executor. It creates an executor with only one thread so it can only execute one task at a time.

The ThreadPoolExecutor class provides a lot of methods to obtain information about its status. We used the getPoolSize(), getActiveCount(), and getCompletedTaskCount() methods in the example to obtain information about the size of the pool, the number of threads, and the number of completed tasks of the executor. You can also use the getLargestPoolSize() method; it returns the maximum number of threads that have been in the pool at a time.

The ThreadPoolExecutor class also provides other methods related to the finalization of the executor. These methods are:

  • shutdownNow(): This shuts down the executor immediately. It doesn't execute pending tasks. It returns a list with all the pending tasks. Tasks that are running when you call this method continue with their execution, but the method doesn't wait for their finalization.
  • isTerminated(): This method returns true if you call either the shutdown() or shutdownNow() method; the executor finishes the process of shutting it down accordingly.
  • isShutdown(): This method returns true if you call the shutdown() method of the executor.
  • awaitTermination(long timeout, TimeUnit unit): This method blocks the calling thread until the tasks of the executor end or a timeout occurs. The TimeUnit class is an enumeration with the following constants: DAYS, HOURS, MICROSECONDS, MILLISECONDS, MINUTES, NANOSECONDS, and SECONDS.
If you want to wait for the completion of tasks, regardless of their duration, use a big timeout, for example, DAYS.
..................Content has been hidden....................

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