How to create, manage Thread pools in Java?

ThreadPool Creation
  1. Executors class provides several static methods to create various types of Thread pools in Java
  2. FixedThreadPool, CachedThreadPool, ScheduledThreadPool, WorkStealingPool are different variants of Thread pools available in java.
  3. A thread pool can be created by calling the below snippet.
ExecutorService fixedPoolExecutorService = Executors.newFixedThreadPool(2);

ThreadPool Management
  1. Thread pools are managed by ExecutorService Interface. We get the handle of ExecutorService while creating the Thread Pool.
  2. ExecutorService provides submit() method to submit your task. For submitting a task, you should create a task either by implementing Runnable or Callable and then pass the task's reference to the submit() method. 
  3. Submit() method is overloaded with submit(Runnable task) and submit(Callable Task) and returns Future in both the cases. Runnable version returns Null when we call future.get() whereas callable returns a value.
  4. The task of the ExecutorService is to enqueue the tasks to a pool of threads. An Idle thread picks the task from the queue, executes it and goes back to the pool again.
  5. calling shutDown() will make ExecutorService no longer taking new tasks
In this example, we create a task and submitted the task twice to a fixed thread pool. The same task is later submitted to the scheduled thread pool and requested the pool to schedule the task after 5 secs.


public class ThreadPoolExample {

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        Callable task = ()->{
            Thread.sleep(1000);
            int result = new Random().nextInt(100);
            System.out.println(Thread.currentThread().getName()+" picked the task, result : "+result);
            return result;
        };

        ExecutorService fixedPoolExecutorService = Executors.newFixedThreadPool(2);
        System.out.println("Submitting the tasks to FixedThreadPool");
        fixedPoolExecutorService.submit(task);
        fixedPoolExecutorService.submit(task);
        fixedPoolExecutorService.shutdown();

        Thread.sleep(1000);

        System.out.println("Submitting the tasks to ScheduledThreadPool");
        ScheduledExecutorService scheduledPoolExecutorService = Executors.newScheduledThreadPool(2);
        scheduledPoolExecutorService.schedule(task, 5, TimeUnit.SECONDS);
        scheduledPoolExecutorService.shutdown();
    }
}

Output
pool-1-thread-2 picked the task, result : 11
pool-1-thread-1 picked the task, result : 33
Submitting the tasks to ScheduledThreadPool
pool-2-thread-1 picked the task, result : 18

Advantages
  • ThreadPool decouples the task creation from task execution. In the case of Thread, they are tightly coupled.

ExecutorService executorService = Executors.newSingleThreadExecutor(); 
//You can always change the implementation to different threadpool here. 
Future<String> future = executorService.execute(() -> "Hello World");
String result = future.get();
 
Thread thread = new Thread(()-> System.out.println("Hello World")); 
// Task is tightly coupled to Thread here

  • When threads are used we are responsible for creating the thread, starting the thread, managing the thread etc., But, when we used Threadpool, we only bothered about submitting the task to the thread pool.



Comments

Popular posts from this blog

Web Security

LDAP - Basics