Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Source Code Analysis of the implementation principle of java Thread Pool

2025-04-13 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces "source code analysis of the implementation principle of java thread pool". In daily operation, I believe that many people have doubts about the source code analysis of the implementation principle of java thread pool. I have consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "source code analysis of the implementation principle of java thread pool". Next, please follow the editor to study!

The origin of thread pool

Background: with the upgrading of computer hardware, our software has the ability to execute tasks with multi-thread. When we are doing multithreaded programming, we need to create threads. If the program concurrency is very high, we will create a large number of threads, and each thread will end up executing a task for a very short time. Creating threads frequently will greatly reduce system performance and increase server overhead, because creating and destroying threads require additional consumption.

At this point, we can use pooling technology to optimize this defect, and the thread pool is born.

The essence of pooling technology is that in order to reuse resources and reduce the overhead of resource creation and destruction in high concurrency scenarios, there is no obvious advantage if the number of concurrency is very small (resources always occupy system memory and have no chance to be used).

Introduction to pooling technology: when is pooling technology? Pooling technology is a programming skill, when the program has high concurrency, it can obviously optimize the program and reduce the extra overhead such as frequent creation and destruction of connections. The pooling technologies we often come into contact with are database connection pooling, thread pooling, object pooling, and so on. The characteristic of pooling technology is that some high-cost resources are maintained in a specific pool (memory), and the minimum number of connections, maximum number of connections, blocking queue, overflow rules and other configurations are specified to facilitate unified management. In general, there will also be some monitoring, compulsory recycling and other supporting functions.

Pooling as a resource usage technology, a typical use case is:

When the cost of obtaining resources is high

When the frequency of requesting resources is high and the total number of resources used is low

In the face of performance problems, when it comes to processing time delays

Classification of pooled technical resources:

System resources called by the system, such as threads, processes, memory allocation, etc.

Remote resources for network communication, such as database connections, socket connections, etc.

Definition and use of thread pool

Thread pool is born in order to avoid the extra overhead of thread creation and thread destruction, so after we define that thread pool is created, we do not need to create threads ourselves, but use thread pool calls to execute our tasks. Let's take a look at how to define and create thread pools.

Option 1: Executors (for understanding only, it is recommended to use option 2)

You can use Executors to create a thread pool, which provides a series of factory methods for creating a thread pool, and the returned thread pool implements the ExecutorService interface.

The ExecutorService interface is a subclass interface of the Executor interface, which is more widely used. It provides a method for thread pool life cycle management and returns a Future object.

In other words, we create a thread pool through Executors, get ExecutorService, and execute asynchronous tasks through ExecutorService (implementing the Runnable interface)

Executors can create several types of thread pools:

NewCachedThreadPool creates a cacheable thread pool. If there are too many threads in the thread pool, the excess thread resources will be reclaimed after 60 seconds. When the task book increases and there are not enough threads, a new thread will be created.

NewFixedThreadPool creates a fixed-length thread pool that controls the maximum number of concurrent threads, and excess threads wait in the queue.

NewScheduledThreadPool creates a fixed-length thread pool that supports scheduled and periodic task execution.

NewSingleThreadExecutor creates a single-threaded thread pool that uses only a single thread to execute tasks, ensuring that tasks are completed in the order in which they are submitted.

Option 2: ThreadPoolExecutor

In the Alibaba development specification, it is stipulated that thread pools are not allowed to be created through Executors, but through ThreadPoolExecutor.

Benefit: let the students who write more clearly the running rules of the thread pool and avoid the risk of resource exhaustion.

Seven parameters of ThreadPoolExecutor:

(1) the number of corePoolSize core threads. The core thread will always be retained and will not be destroyed.

(2) the maximum number of threads in maximumPoolSize. When the core thread can not meet the needs of the task, the system will create a new thread to execute the task.

(3) keepAliveTime survival time, how long the thread other than the core thread will be idle will be destroyed.

(4) timeUnit represents the time unit in which the thread survives.

(5) BlockingQueue blocking queue

If the number of tasks being executed exceeds the maximum number of threads, it can be stored in the queue, and when there are free resources in the thread pool, the task can be taken out of the queue to continue execution.

There are several types of queues: LinkedBlockingQueue ArrayBlockingQueue SynchronousQueue TransferQueue.

(6) threadFactory thread factory, which is used to create threads, can customize threads, for example, we can define thread group names, which is very helpful when troubleshooting jstack problems.

(7) rejectedExecutionHandler rejection strategy

When all threads (the maximum number of threads) are busy and the task queue is full of tasks, the reject policy is executed.

JDK provides us with four refusal strategies, which we must all be familiar with.

AbortPolicy: discards the task and throws an exception RejectedExecutionException. Default

DiscardPolicy: discard the latest tasks and do not throw exceptions.

DiscardOldestPolicy: throw away the task with the longest queue, which is the oldest task.

CallerRuns: the task is handled by the caller (the thread that submits the asynchronous task).

Implementation principle of Thread Pool

To implement a thread pool, we need to care about the ThreadPoolExecutor class, because Executors also creates a thread pool through the new ThreadPoolExecutor object.

If you look at the class inheritance relationship of ThreadPoolExecutor, you can see why the thread pool created by Executors returns ExecutorService, because ThreadPoolExecutor is the implementation class of the ExecutorService interface, and Executors thread pool creation is essentially a created ThreadPoolExecutor object.

Let's take a look at the source code of ThreadPoolExecutor, starting with the variables defined in ThreadPoolExecutor, constants:

/ / the composite type variable is an atomic integer control state (running status | number of active threads in the thread pool) private final AtomicInteger ctl = new AtomicInteger (ctlOf (RUNNING, 0)); private static final int COUNT_BITS = Integer.SIZE-3; / / low 29-bit private static final int CAPACITY = (1

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report