Java — Thread Pools (Executor Framework) | Code Factory

  • Creating a new thread for every job may create performance on memory problems, to overcome this we should go for Thread Pool.
  • Thread pool is a pool of already created threads, ready to do out job.
  • Java 1.5v introduces thread pool framework to implement thread pools. Thread Pool also know as executor framework.
  • We can create a thread pool as foolows.
ExecutorService service = Executors.newFixedThreadPool(3);
  • We can submit a Runnable job by using a submit method service.submit(job).
  • We can shutdown executor service by using shutdown method service.shutdown().
package com.example.thread;import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
* @author code.factory
public class ExecutorTest {
public static void main(String... args) {
PrintJob jobs[] = {
new PrintJob("Narendra"),
new PrintJob("Amit"),
new PrintJob("Yogi"),
new PrintJob("Rupani"),
new PrintJob("Mukesh"),
new PrintJob("Anil"),
ExecutorService service = Executors.newFixedThreadPool(3);
for(PrintJob job : jobs) {
class PrintJob implements Runnable {
String name;
public PrintJob(String name) { = name;

public void run() {
System.out.println(name + " job started by thread " + Thread.currentThread().getName());
try {
} catch(InterruptedException e) {
Narendra job started by thread pool-1-thread-1
Yogi job started by thread pool-1-thread-3
Amit job started by thread pool-1-thread-2
Rupani job started by thread pool-1-thread-1
Anil job started by thread pool-1-thread-3
Mukesh job started by thread pool-1-thread-2
  • In the above exmple 3 threads are responsible to execute 6 jobs. So that a single thread can be reuse for multiple jons.
  • While designing web servers and application servers we can use thread pool concept.




Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Day 10 of #100DaysOfCode

Using R to Extract The Beauty and Complexity of The Beatles’ Songs

Control Xiaomi Yeelight Bulbs with Python

I Replaced Supervisor With the Docker CMD Instruction

Cutup #6 Breadcrumb bar with microdata

Executing Application Modernization

Part I: Using Deephaven to Analyze Potential Pairs for Pair Trading

Work smart, not hard — Part 1

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Code Factory

Code Factory

More from Medium

Concurrency in Java: Executor Service (Part 1)

Unit Testing Apache Camel

Single Responsibility Principle (SRP)

Spring cloud config: Smaller details with bigger impacts