Java Thread Pooling
Contents
Java Thread Pooling : Concept
- Suppose we have 10 jobs in wait queue to be executed and we have 5 worker threads, then each of 5 worker threads will be assigned single job for execution.
- By the time when job is finished, thread selects another job from the job wait queue and start executing that job.
Thus we can say that Java Thread Pooling is -
- A thread pool manages the pool of worker threads,
- A thread pool contains queue which keeps track of jobs waiting for execution.
- A thread pool manages the collection of Runnable threads and worker threads execute Runnable from the queue.
Java Example : Thread Pooling
package com.c4learn.thread; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; class WorkerThread implements Runnable { private String jobId; public WorkerThread(String s){ this.jobId=s; } public void run() { String tName = Thread.currentThread().getName(); System.out.println(tName +" (Start) Job = "+ jobId); processmessage(); System.out.println(tName + " (End)"); } private void processmessage() { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } } public class ThreadPool { public static void main(String[] args) { ExecutorService executor = Executors.newFixedThreadPool(5); for (int i = 0; i < 10; i++) { Runnable worker = new WorkerThread("" + i); executor.execute(worker); } executor.shutdown(); while (!executor.isTerminated()) { } System.out.println("Finished all Jobs"); } }
Output :
pool-1-thread-1 (Start) Job = 0 pool-1-thread-5 (Start) Job = 4 pool-1-thread-2 (Start) Job = 1 pool-1-thread-3 (Start) Job = 2 pool-1-thread-4 (Start) Job = 3 pool-1-thread-5 (End) pool-1-thread-1 (End) pool-1-thread-5 (Start) Job = 5 pool-1-thread-2 (End) pool-1-thread-4 (End) pool-1-thread-3 (End) pool-1-thread-1 (Start) Job = 6 pool-1-thread-3 (Start) Job = 9 pool-1-thread-4 (Start) Job = 8 pool-1-thread-2 (Start) Job = 7 pool-1-thread-1 (End) pool-1-thread-2 (End) pool-1-thread-4 (End) pool-1-thread-5 (End) pool-1-thread-3 (End) Finished all Jobs
Explanation :
A. Creating Pool of Worker Threads :
Below line will create group of worker threads -
ExecutorService executor = Executors.newFixedThreadPool(5);
A fixed-size thread pool creates threads as tasks are submitted, up to the maximum pool size. In this case our maximum pool size is 5.
B. Submitting job :
Now we have 10 jobs to be executed concurrently using the 5 worker threads.
for (int i = 0; i < 10; i++) { Runnable worker = new WorkerThread("" + i); executor.execute(worker); }
The ExecutorService adds life cycle methods to the Executor, which allows to shutdown the Executor and to wait for termination.