Java / Java Multithreading and Concurrency

Using Executor Framework for Thread Pooling

This tutorial will teach you how to use the Executor framework in Java for thread pooling. You will learn how to limit the number of threads created and enhance the performance of…

Tutorial 4 of 5 5 resources in this section

Section overview

5 resources

Introduces multithreading concepts to enable concurrent execution.

Tutorial: Using Executor Framework for Thread Pooling in Java

1. Introduction

In this tutorial, we will delve into the Java Executor framework and understand how to leverage it for thread pooling.

Thread pooling is a powerful concept that optimizes the use of system resources by reusing existing threads rather than continuously creating new ones. By the end of this tutorial, you will learn how to manage and control threads effectively in a multi-threaded environment.

Prerequisites: Basic knowledge of Java programming and understanding of threads.

2. Step-by-Step Guide

In Java, the Executor framework is a powerful tool that allows you to manage and control thread execution in concurrent Java applications. The Executor framework provides a pool of threads, which is a group of worker threads that are waiting for tasks to execute.

How does thread pool work?

When a new task is submitted to the thread pool, it will try to use a dormant (idle) thread in the pool if available. If all threads are active, the task will wait in a queue. As soon as a thread becomes idle, it can pick up a task from the queue and start executing it.

Here's how you can create a simple thread pool using Executor framework:

ExecutorService executorService = Executors.newFixedThreadPool(10);

In this example, we're creating a fixed-size thread pool of 10 threads. The newFixedThreadPool method returns an instance of ExecutorService, which can be used to manage the threads.

3. Code Examples

Example 1: Basic Thread Pool

Here's a simple example of using a thread pool to execute tasks:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(5);

        for (int i = 0; i < 10; i++) {
            Runnable worker = new WorkerThread("" + i);
            executorService.execute(worker);
        }
        executorService.shutdown();
        while (!executorService.isTerminated()) {
        }
        System.out.println("Finished all threads");
    }
}

class WorkerThread implements Runnable {
    private String command;
    public WorkerThread(String s){
        this.command=s;
    }
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+" Start. Command = "+command);
        processCommand();
        System.out.println(Thread.currentThread().getName()+" End.");
    }

    private void processCommand() {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

In the above example, we have a pool of 5 threads. We have 10 tasks to execute. Once we submit these tasks to the executor, it starts executing them using the threads in the pool.

Expected Output:

pool-1-thread-1 Start. Command = 0
pool-1-thread-2 Start. Command = 1
pool-1-thread-3 Start. Command = 2
pool-1-thread-4 Start. Command = 3
pool-1-thread-5 Start. Command = 4
pool-1-thread-1 End.
pool-1-thread-6 Start. Command = 5
pool-1-thread-2 End.
pool-1-thread-7 Start. Command = 6
pool-1-thread-3 End.
pool-1-thread-8 Start. Command = 7
pool-1-thread-4 End.
pool-1-thread-9 Start. Command = 8
pool-1-thread-5 End.
pool-1-thread-10 Start. Command = 9
Finished all threads

4. Summary

In this tutorial, we learned how to use the Executor framework in Java to create a thread pool. We also learned how to submit tasks to the thread pool and control the execution of threads.

For further learning, check out the Java documentation on ExecutorService.

5. Practice Exercises

Exercise 1: Create a thread pool with a single thread and submit five tasks to it. Observe the order of execution.

Exercise 2: Create a thread pool with five threads. Submit tasks that have different sleep times and observe the order of execution.

Exercise 3: Modify the above program to use Callable and Future to get the result of computation.

Tips for further practice: Try to play with different types of thread pools provided by the Executors class like newCachedThreadPool(), newSingleThreadExecutor(), etc.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Text Diff Checker

Compare two pieces of text to find differences.

Use tool

JavaScript Minifier & Beautifier

Minify or beautify JavaScript code.

Use tool

Watermark Generator

Add watermarks to images easily.

Use tool

HTML Minifier & Formatter

Minify or beautify HTML code.

Use tool

JSON Formatter & Validator

Beautify, minify, and validate JSON data.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help