preface

In the daily development process always to single thread thinking to code, did not take into account the multithreaded state of the state of the operation. The result is too many requests for the application to respond to. In order to solve the problem of excessive requests, the concept of thread pool was derived. Through the “pool” idea, thus reasonable processing requests. This article records the use of Java thread pool and how it works, if any error, welcome to correct. Summarized a Java multithreading atlas to share with you

What is a thread pool?

Thread pooling is a software design pattern used to implement concurrent execution of computer programs. A thread pool maintains multiple threads waiting for tasks to be assigned by the scheduler for concurrent execution, a model that improves performance and avoids execution delays caused by frequent creation and destruction of threads for short-term tasks.

What problem does thread pooling solve?

Talking about thread pools starts with the life cycle of a thread.

You can see from the figure that no matter how long the task is executed, each thread experiences a life-to-death state. Thread pools are used to prevent repeated threads from being created, thereby saving time on threads New to Runnable and Running to Terminated. At the same time, it can reuse threads to minimize the saving of system resources and improve the response speed.

Use of thread pools

Creation of a thread pool

Create a thread pool using ThreadPoolExecutor and configure seven parameters

public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler)

corePoolSize

The maximum number of core threads in the thread pool

maximumPoolSize

Maximum number of threads in the thread pool

keepAliveTime

The lifetime of non-core threads that are idle

unit

KeepAliveTime is a unit of keepAliveTime, such as seconds, minutes, and hours

workQueue

Blocking queue type

threadFactory

Thread factory, used to configure the name of the thread, whether it is a daemon thread, etc

handler

Thread pool rejection policy

Common blocking queue

ArrayBlockingQueue

Bounded blocking queues for the underlying array-based implementation

LinkedBlockingQueue The underlying block queue based on a single list. The size can be configured. The unconfigured size defaults to integer.max_value

Thread factory

It is mandatory to specify thread names in the Alibaba Java Development Manual

Because you work with hutool a lot, it also contains a wrapper for ThreadFactory, so you can easily specify the name

ThreadFactory threadFactory = ThreadFactoryBuilder.create().setNamePrefix(“myThread-“).build();

Rejection policies

When the number of worker threads in the thread pool exceeds maximumPoolSize, the thread will no longer accept the task, and the corresponding rejection policy will be implemented. Currently, four rejection strategies are supported:

1. AbortPolicy (default) : discard task and throw RejectedExecutionException anomalies

CallerRunsPolicy: handled by the caller

3.DiscardOldestPolicy: Discards the first task in the queue and reenters the queue

4.DiscardPolicy: Discards the task without throwing an exception

Thread pool execution logic

/ / create a thread factory ThreadFactory ThreadFactory = ThreadFactoryBuilder. The create () setNamePrefix (" myThread - "). The build (); ThreadPoolExecutor ThreadPoolExecutor = new ThreadPoolExecutor(5, 10, 10, timeunit.seconds, new ArrayBlockingQueue<>(100), threadFactory, new ThreadPoolExecutor.AbortPolicy());Copy the code

The execute () method

// Combination value; Private Final AtomicInteger CTL = new AtomicInteger(ctlOf(RUNNING, 0));Copy the code
Public void execute(Runnable command) {// If (command == null) throw new NullPointerException(); Int c = ctl.get(); If (workerCountOf(c) < corePoolSize) {if (addWorker(command, true)) return; c = ctl.get(); If (isRunning(c) && workqueue.offer (command)) {int recheck = ctl.get(); // If the thread pool is not in the Running state, remove the newly added task and execute the rejection policy if (! isRunning(recheck) && remove(command)) reject(command); Else if (workerCountOf(recheck) == 0) addWorker(null, false); } // Failed to add task, execute reject policy else if (! addWorker(command, false)) reject(command); } // addWorker() completes the thread creationCopy the code

Execute the process

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

The last

I here organized a Java thread pool information document Java systematic information :(including Java core knowledge, Spring series of family barrel, interview topics and 21 years of the latest Internet real questions, e-books, etc.) have the need of friends can pay attention to the public number [procedures yuan small wan] can be obtained.