Executors class provides factory and utility methods for creating Executor, ExecutorService and Callable classes.

Mostly used methods are the ones that create ExecutorService instances. Executors have 2 defining properties:

  1. Task queue to hold submitted tasks
  2. Worker threads to perform the operations

 

Below are the some examples showing Executors usage:

  • Executors.newSingleThreadExecutor(): Creates an Executor that uses a single worker thread operating off an unbounded queue.
public static void singleThreaded() {
    ExecutorService executorService = Executors.newSingleThreadExecutor();
    System.out.printf("Thread pool details: %s%n", executorService);
}
  • Executors.newFixedThreadPool(int nThreads): Creates a thread pool that reuses a fixed number of threads operating off a shared unbounded queue. At any point, at most nThreads threads will be active processing tasks.
public static void fixedSize() {
    ExecutorService executorService = Executors.newFixedThreadPool(5);
    System.out.printf("Thread pool details: %s%n", executorService);
}
  • Executors.newCachedThreadPool():¬†Creates a thread pool that creates new threads as needed, but will reuse previously constructed threads when they are available.
public static void cached() {
    ExecutorService executorService = Executors.newCachedThreadPool();
    System.out.printf("Thread pool details: %s%n", executorService);
}
  • Executors.newScheduledThreadPool(int corePoolSize):¬†Creates a thread pool that can schedule commands to run after a given delay, or to execute periodically.
public static void scheduled() {
    ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(5);
    System.out.printf("Thread pool details: %s%n", scheduledExecutorService);
}

 

 

 

 

Leave a Reply

Close Menu