Thread pools via Executors

One step further, and we introduce the helper class, Executors. This class exposes several types of thread pools using the following methods:

  • newSingleThreadExecutor(): This is a thread pool that manages only one thread with an unbounded queue, which only executes one task at a time:
ExecutorService executor 
= Executors.newSingleThreadExecutor();
  • newCachedThreadPool(): This is a thread pool that creates new threads and removes idle threads (after 60 seconds) as they are needed; the core pool size is 0 and the maximum pool size is Integer.MAX_VALUE (this thread pool expands when demand increases and contracts when demand decreases):
ExecutorService executor = Executors.newCachedThreadPool();
  • newFixedThreadPool(): This is a thread pool with a fixed number of threads and an unbounded queue, which creates the effect of an infinite timeout (the core pool size and the maximum pool size are equal to the specified size):
ExecutorService executor = Executors.newFixedThreadPool(5);
  • newWorkStealingThreadPool(): This a thread pool based on a work-stealing algorithm (it acts as a layer over a fork/join framework):
ExecutorService executor = Executors.newWorkStealingPool();
  • newScheduledThreadPool(): A thread pool that can schedule commands to run after a given delay, or to execute periodically (we can specify the core pool size):
ScheduledExecutorService executor 
= Executors.newScheduledThreadPool(5);
..................Content has been hidden....................

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