SoFunction
Updated on 2025-03-03

Several ways and differences in creating thread pools in Java

Several ways and differences in creating thread pools in Java

Updated: November 6, 2024 11:01:09 Author: The-Venus
There are many ways to create thread pools, mainly through the Executors tool class provided by the Java package. This article introduces several common thread pool types and their differences, and explains them in detail through code examples. Friends who need it can refer to it.

1. FixedThreadPool

//Create a fixed-size thread pool, simulate submitting 10 tasks to the thread pool.import ;
import ;

public class FixedThreadPoolExample {
    public static void main(String[] args) {
        ExecutorService fixedThreadPool = (3); // Create a fixed thread pool with 3 threads        
        for (int i = 1; i <= 10; i++) {
            final int task = i;
            (() -> {
                ("Execute Tasks" + task + ", thread:" + ().getName());
            });
        }
        
        ();
    }
}
  • Features: Create a fixed-size thread pool, where the specified number of threads is always maintained.

  • Applicable scenarios: Suitable for tasks with fixed concurrency numbers, such as quantitative short-term concurrency tasks.

  • advantage: Can effectively control the number of threads and avoid excessive resource consumption.

  • shortcoming: If all threads are executing tasks and new tasks are constantly submitted, it may cause the waiting queue to be too long.

2. CachedThreadPool

//Create a cache thread pool to process tasks and simulate 10 tasks to execute concurrently.
import ;
import ;

public class CachedThreadPoolExample {
    public static void main(String[] args) {
        ExecutorService cachedThreadPool = ();
        
        for (int i = 1; i <= 10; i++) {
            final int task = i;
            (() -> {
                ("Execute Tasks" + task + ", thread:" + ().getName());
            });
        }
        
        ();
    }
}
  • Features: Create a thread pool that can be automatically expanded as needed, and will be recycled after 60 seconds of free thread.
  • Applicable scenarios: Suitable for performing a large number of time-consuming asynchronous tasks.
  • advantage: The number of threads is not limited (subject to system resources), and it is better for scenarios where tasks are short, concurrency is large, but unstable.
  • shortcoming: If the task grows too fast, a large number of threads will be created, which may cause OOM (Out of Memory) exception.

3. SingleThreadExecutor

//Create a single thread pool to execute multiple tasks in sequence.import ;
import ;

public class SingleThreadExecutorExample {
    public static void main(String[] args) {
        ExecutorService singleThreadExecutor = ();
        
        for (int i = 1; i <= 5; i++) {
            final int task = i;
            (() -> {
                ("Execute Tasks" + task + ", thread:" + ().getName());
            });
        }
        
        ();
    }
}
  • Features: Create a single-threaded thread pool, and there is always only one worker thread.
  • Applicable scenarios: Suitable for scenarios where tasks need to be executed sequentially, avoiding the complexity of multi-threaded concurrency.
  • advantage: It can ensure that tasks are executed in order and are suitable for a single task queue.
  • shortcoming: Low performance and is not suitable for scenarios where high concurrency is required.

4. ScheduledThreadPool

//Create a thread pool that supports timed and periodic execution of tasks. The sample tasks are executed every 2 seconds, and a total of 3 times.import ;
import ;
import ;

public class ScheduledThreadPoolExample {
    public static void main(String[] args) {
        ScheduledExecutorService scheduledThreadPool = (2); // Create a timed thread pool with 2 threads        
        (() -> {
            ("Timed task execution, thread:" + ().getName());
        }, 0, 2, ); // Start after 0 seconds delay, and execute tasks every 2 seconds        
        // The program will close the thread pool after running for 5 seconds        try {
            (5000);
        } catch (InterruptedException e) {
            ();
        }
        
        ();
    }
}
  • Features: Create a thread pool that supports timed or periodic task execution.
  • Applicable scenarios: Suitable for performing timing or periodic tasks, such as timers, timing checks, etc.
  • advantage: It can easily realize periodic task management.
  • shortcoming: The processing capability of high-concurrency tasks is weak and is usually used in scenarios with small tasks.

5. WorkStealingPool (introduced by Java 8)

//Create a thread pool based on task decomposition to execute multiple tasks in parallel, suitable for processing small tasks that need to be split.import ;
import ;
import ;

public class WorkStealingPoolExample {
    public static void main(String[] args) throws InterruptedException {
        ExecutorService workStealingPool = (); // Create a work-stealing thread pool with the default number of threads as CPU cores        
        for (int i = 1; i <= 8; i++) {
            final int task = i;
            (() -> {
                ("Execute Tasks" + task + ", thread:" + ().getName());
                try {
                    (1);
                } catch (InterruptedException e) {
                    ();
                }
            });
        }
        
        // Let the main thread wait for the subtask to be completed        (3, );
        ();
    }
}
  • Features:based onForkJoinPoolImplementation, suitable for parallel processing of splitting large tasks into small tasks. The number of threads is the number of processor cores by default.
  • Applicable scenarios: Suitable for handling more complex parallel tasks, such as partitioning and conquer algorithms.
  • advantage: Dynamic load balancing of tasks can be achieved through the "work theft" algorithm, which can effectively improve the utilization rate of multi-core CPUs.
  • shortcoming: Due to the unfixed number of threads, it may use more resources and is not suitable for all applications.

Summary of the difference

Thread pool type Thread count control Features Applicable scenarios
FixedThreadPool Fixed quantity Fixed thread count, suitable for stable task concurrency Fixed concurrent tasks
CachedThreadPool Automatic expansion Dynamic expansion, automatic recycling of idle threads, suitable for short tasks but unstable concurrency Short-term asynchronous concurrent tasks
SingleThreadExecutor Single thread Execute tasks in a single thread order to ensure order Sequentially executed tasks
ScheduledThreadPool Controllable core thread count Supports timing or periodic tasks Timed tasks, periodic tasks
WorkStealingPool Default CPU core count Based on task splitting and parallel processing, improve multi-core CPU utilization Parallel computing and multitasking decomposition

The above are the details of the ways to create thread pools in Java and the differences. For more information about creating thread pools in Java, please pay attention to my other related articles!

  • Java
  • create
  • Thread pool

Related Articles

  • Methods supported by multiple data sources in SpringBoot projects

    This article mainly introduces the methods of multi-data source support in SpringBoot project, and mainly introduces how to use SpringDataJpa technology to support data sources of multiple databases in SpringBoot project. If you are interested, you can learn about it.
    2017-10-10
  • SpringCloud distributed link tracking method

    This article mainly introduces the SpringCloud distributed link tracking method. The editor thinks it is quite good. I will share it with you now and give you a reference. Let's take a look with the editor
    2019-03-03
  • Solve the problem of JDK exception handling No appropriate protocol

    This article mainly introduces the solution to the problem of JDK exception handling No appropriate protocol, which is of great reference value. I hope it will be helpful to everyone. If there are any errors or no complete considerations, I hope you will be very encouraged.
    2024-06-06
  • Detailed explanation of how to compare array judging elements in Java

    This article mainly introduces several ways to compare array judgment elements in Java. It is very good and has certain reference value. Please refer to it if you need it.
    2018-07-07
  • Talking about several common dependency injection problems in spring boot

    This article mainly introduces several common dependency injection problems in spring boot, which are of good reference value and hope it will be helpful to everyone. If there are any mistakes or no complete considerations, I hope you will be very grateful for your advice
    2021-09-09
  • Detailed explanation of the example of java interface performance from 20s to 500ms

    This article mainly introduces detailed explanations of the operation techniques for optimizing Java interface performance from 20s to 500ms. Friends in need can refer to it for reference. I hope it can be helpful. I wish you more progress and get promoted as soon as possible to get a salary increase as soon as possible.
    2022-07-07
  • How to turn on and off kafka consumption in springboot

    In Kafka consumers, by turning off the automatic consumption configuration, using a custom container factory, and setting the id on the consumption listener, the consumption opening and closing can be manually controlled. This is a method summarized based on personal experience and aims to help other developers.
    2024-12-12
  • Teach you how to easily create a java video player

    This article mainly introduces in detail how to write your own Java video player, which has certain reference value. Interested friends can refer to it.
    2017-06-06
  • A brief analysis of the adapter HandlerAdapter in SpringMVC

    This article mainly introduces the relevant information about the adapter HandlerAdapter in SpringMVC. This article introduces you very detailedly and has certain reference value for your study or work. Friends who need it can refer to it.
    2021-01-01
  • SpringBoot MyBatis Nanny-level Integration Tutorial

    Because of the convenience of Spring Boot framework development, it is very simple to integrate Spring Boot and data access layer framework (such as MyBatis). It mainly introduces the corresponding dependency starter and sets the database-related parameters.
    2022-06-06

Latest Comments