Course
Thread Pools
Java Tutorial
This Java tutorial is tailored for newcomers, offering a journey from basic principles to complex Java programming techniques. Completing this tutorial equips you with a solid understanding of Java, preparing you for advanced learning. You'll emerge ready to tackle the challenges of becoming a top-tier software engineer, with the skills to innovate and excel in the vast world of software development.
Thread Pools
Thread Pools
A thread pool is a collection of pre-initialized threads. The general plan behind a thread pool is to form variety of threads at method startup and place them into a pool, wherever they sit and expect work. once a server receives a call for participation, it awakens a thread from this pool−if one is available−and passes it the request for service. Once the thread completes its service, it returns to the pool and awaits a lot of work. If the pool contains no accessible thread, the server waits till one becomes free.
Why Use Thread Pools in Java?
- It saves time as a result of there's no need to produce new thread.
Creating Thread Pools in Java
Java provides a java.util.concurrent.Executors class provides couple of methods to create a thread pools.
Executors Class Methods
Following are few important and useful methods this class to create Thread Pools
Creating a Thread Pool Using newFixedThreadPool() Method
A fixed thread pool obtainted by calling the static newFixedThreadPool() method of Executors class.
Syntax
ExecutorService fixedPool = Executors.newFixedThreadPool(2);
Where,
- Maximum 2 threads will be active to process tasks.
- If more than 2 threads are submitted then they are held in a queue until threads become available.
- A new thread is created to take its place if a thread terminates due to failure during execution shutdown on executor is not yet called.
- Any thread exists till the pool is shutdown.
Example: Creating a Thread Pool Using newFixedThreadPool() Method
The following TestThread program shows usage of Executors newFixedThreadPool() method to create a thread pool of two threads. We're using a ThreadPoolExecutor object and initialized with newFixedThreadPool(2), a fix thread pool of size 2. Then we're printing various attributes of the threadpool. Then we're adding few threads to the executor and then same attributes of threadpool are printed to reflect the changes.
package com.tutorialspoint;
import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.ThreadPoolExecutor;import java.util.concurrent.TimeUnit;
public class TestThread { public static void main(final String[] arguments) throws InterruptedException { ExecutorService executor = Executors.newFixedThreadPool(2);
// Cast the object to its class type ThreadPoolExecutor pool = (ThreadPoolExecutor) executor;
//Stats before tasks execution System.out.println("Largest executions: " + pool.getLargestPoolSize()); System.out.println("Maximum allowed threads: " + pool.getMaximumPoolSize()); System.out.println("Current threads in pool: " + pool.getPoolSize()); System.out.println("Currently executing threads: " + pool.getActiveCount()); System.out.println("Total number of threads(ever scheduled): " + pool.getTaskCount());
executor.submit(new Task()); executor.submit(new Task()); executor.submit(new Task()); executor.submit(new Task());
//Stats after tasks execution System.out.println("Core threads: " + pool.getCorePoolSize()); System.out.println("Largest executions: " + pool.getLargestPoolSize()); System.out.println("Maximum allowed threads: " + pool.getMaximumPoolSize()); System.out.println("Current threads in pool: " + pool.getPoolSize()); System.out.println("Currently executing threads: " + pool.getActiveCount()); System.out.println("Total number of threads(ever scheduled): " + pool.getTaskCount());
executor.shutdown(); }
static class Task implements Runnable {
public void run() { try { Long duration = (long) (Math.random() * 5); System.out.println("Running Task! Thread Name: " + Thread.currentThread().getName()); TimeUnit.SECONDS.sleep(duration); System.out.println("Task Completed! Thread Name: " + Thread.currentThread().getName()); } catch (InterruptedException e) { e.printStackTrace(); } } }}
Output
Largest executions: 0Maximum allowed threads: 2Current threads in pool: 0Currently executing threads: 0Total number of threads(ever scheduled): 0Core threads: 2Largest executions: 2Maximum allowed threads: 2Current threads in pool: 2Currently executing threads: 2Total number of threads(ever scheduled): 4Running Task! Thread Name: pool-1-thread-2Running Task! Thread Name: pool-1-thread-1Task Completed! Thread Name: pool-1-thread-2Running Task! Thread Name: pool-1-thread-2Task Completed! Thread Name: pool-1-thread-1Running Task! Thread Name: pool-1-thread-1Task Completed! Thread Name: pool-1-thread-2Task Completed! Thread Name: pool-1-thread-1
Here although, we've submitted four threads but only two threads are executed as ThreadPool is fixed to accept only two threads.
Creating a Thread Pool Using newCachedThreadPool() Method
A cached thread pool obtainted by calling the static newCachedThreadPool() method of Executors class.
Syntax
ExecutorService executor = Executors.newCachedThreadPool();
Where,
- newCachedThreadPool method creates an executor having an expandable thread pool.
- Such an executor is suitable for applications that launch many short-lived tasks.
Example: Creating a Thread Pool Using newCachedThreadPool() Method
The following TestThread program shows usage of Executors newCachedThreadPool() method to create a expandable thread pool of threads. We're using a ThreadPoolExecutor object and initialized with newCachedThreadPool(). Then we're printing various attributes of the threadpool. Then we're adding few threads to the executor and then same attributes of threadpool are printed to reflect the changes.
package com.tutorialspoint;
import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.ThreadPoolExecutor;import java.util.concurrent.TimeUnit;
public class TestThread { public static void main(final String[] arguments) throws InterruptedException { ExecutorService executor = Executors.newCachedThreadPool();
// Cast the object to its class type ThreadPoolExecutor pool = (ThreadPoolExecutor) executor;
//Stats before tasks execution System.out.println("Largest executions: " + pool.getLargestPoolSize()); System.out.println("Maximum allowed threads: " + pool.getMaximumPoolSize()); System.out.println("Current threads in pool: " + pool.getPoolSize()); System.out.println("Currently executing threads: " + pool.getActiveCount()); System.out.println("Total number of threads(ever scheduled): " + pool.getTaskCount());
executor.submit(new Task()); executor.submit(new Task()); executor.submit(new Task()); executor.submit(new Task());
//Stats after tasks execution System.out.println("Core threads: " + pool.getCorePoolSize()); System.out.println("Largest executions: " + pool.getLargestPoolSize()); System.out.println("Maximum allowed threads: " + pool.getMaximumPoolSize()); System.out.println("Current threads in pool: " + pool.getPoolSize()); System.out.println("Currently executing threads: " + pool.getActiveCount()); System.out.println("Total number of threads(ever scheduled): " + pool.getTaskCount());
executor.shutdown(); }
static class Task implements Runnable {
public void run() { try { Long duration = (long) (Math.random() * 5); System.out.println("Running Task! Thread Name: " + Thread.currentThread().getName()); TimeUnit.SECONDS.sleep(duration); System.out.println("Task Completed! Thread Name: " + Thread.currentThread().getName()); } catch (InterruptedException e) { e.printStackTrace(); } } }}
Output
Largest executions: 0Maximum allowed threads: 2147483647Current threads in pool: 0Currently executing threads: 0Total number of threads(ever scheduled): 0Core threads: 0Largest executions: 4Maximum allowed threads: 2147483647Current threads in pool: 4Currently executing threads: 4Total number of threads(ever scheduled): 4Running Task! Thread Name: pool-1-thread-2Running Task! Thread Name: pool-1-thread-4Running Task! Thread Name: pool-1-thread-3Running Task! Thread Name: pool-1-thread-1Task Completed! Thread Name: pool-1-thread-3Task Completed! Thread Name: pool-1-thread-4Task Completed! Thread Name: pool-1-thread-2Task Completed! Thread Name: pool-1-thread-1
Creating a Thread Pool Using newScheduledThreadPool() Method
A scheduled thread pool obtainted by calling the static newScheduledThreadPool() method of Executors class.
Syntax
ExecutorService executor = Executors.newScheduledThreadPool(1);
Example: Creating a Thread Pool Using newScheduledThreadPool() Method
The following TestThread program shows usage of Executors newScheduledThreadPool() method to create a thread pool of a thread. We're using a ScheduledExecutorService object as scheduler and initialized with newScheduledThreadPool(). We've created a ScheduledFuture object to schedule a task to execute every two seconds after an initial delay of two seconds. Using scheduler, we scheduled the task to run for ten seconds.
package com.tutorialspoint;
import java.util.concurrent.Executors;import java.util.concurrent.ScheduledExecutorService;import java.util.concurrent.ScheduledFuture;import java.util.concurrent.TimeUnit;
public class TestThread {
public static void main(final String[] arguments) throws InterruptedException { final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
final ScheduledFuture<?> beepHandler = scheduler.scheduleAtFixedRate(new BeepTask(), 2, 2, TimeUnit.SECONDS);
scheduler.schedule(new Runnable() {
@Override public void run() { beepHandler.cancel(true); scheduler.shutdown(); } }, 10, TimeUnit.SECONDS); }
static class BeepTask implements Runnable {
public void run() { System.out.println("beep"); } }}
Output
beepbeepbeepbeepbeep