Do you know anything about Java thread pools? Have you ever used a thread pool? Let’s start with the thread pool core parameters… I’m sorry. I’ll check it later.

For the sake of decency, let’s take a look at some common thread pool interview questions.

Why thread pools?

  1. Thread reuse. If you need to start 1000 threads to execute the program, the system will create 1000 threads. If you use the thread pool to execute 1000 tasks, you do not need to start 1000 threads, just need to set corePoolSize core thread size, the maximum number of threads. The queue size can reuse thread replacement tasks, and 1000 threads are not inefficient, meaning that more threads are not necessarily more efficient. Therefore, we recommend multithreading in the actual development of multithreaded environment.

  2. Better management of threads. ThreadPoolExecutor can control the number of threads and set the number of queues and saturation policies based on actual application scenarios.

What about the thread pool core parameters?

  • CorePoolSize: core thread size. The thread pool keeps running, so the core thread doesn’t stop.

  • MaximumPoolSize: specifies the maximum number of threads in a thread pool. Number of non-core threads =maximumPoolSize-corePoolSize

  • KeepAliveTime: indicates the heartbeat time of non-core threads. If a non-core thread does not run a task within keepAliveTime, the non-core thread dies.

  • WorkQueue: blocking queue. ArrayBlockingQueue, LinkedBlockingQueue, etc.

  • DefaultHandler: Saturation policy.

  • ThreadFactory: ThreadFactory. Create a new thread factory.

Execute Task adding process?

  1. The thread pool executes the execute/submit method to add a task to the thread pool. When the task is smaller than corePoolSize, a new thread can be created in the thread pool.

  2. When the task is greater than the number of core threads corePoolSize, the task is added to the blocking queue.

  3. If the blocking queue is full, a new thread needs to be created in the thread pool by comparing the maximumPoolSize parameter. If the number of threads is greater than maximumPoolSize, the number of threads in the current set thread pool can no longer be processed, and the saturation policy is implemented.

You know the saturation strategy?

Above, we said that when the number of threads is greater than maximumPoolSize, the saturation policy is implemented. There are four saturation strategies in the ThreadPoolExecutor class. Implement the RejectedExecutionHandler interface.

  • AbortPolicy: An error occurs when a thread task is discarded. Default saturation policy.

  • DiscardPolicy: Discards thread tasks without reporting errors.

  • DiscardOldestPolicy: Discards the first workQueue task and requeues the task from the latest thread.

  • CallerRunsPolicy: Threads outside the thread pool directly call the run method.

Let’s look at how the saturation policy is used in code.

import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; /** * @author: jiaolian * @date: Created in 2021-02-20 16:28 * @description: Thread pool discard policy * @modified By: */ Public class AbortTest {private static final int THREAD_COUNT = 50; private static final CountDownLatch COUNT_DOWN_LATCH = new CountDownLatch(THREAD_COUNT); private static final AtomicInteger ATOMIC_INTEGER = new AtomicInteger(1); Public static void main(String[] args) throws InterruptedException {// Create a thread pool, ThreadPoolExecutor ThreadPoolExecutor = new threadPoolExecutor (3,5,1, timeunit.seconds, new ArrayBlockingQueue<Runnable>(20),new ThreadPoolExecutor.AbortPolicy()); AbortPolicy Discarding an error. Discardoldoldestpolicy Discarding the task at the head of the queue and executing the task of the current thread //CallerRunsPolicy directly invoke the run method // Submit the thread for (int i=0; i<THREAD_COUNT; i++) { threadPoolExecutor.execute(()->{ try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+" execute!" +ATOMIC_INTEGER.getAndIncrement()); COUNT_DOWN_LATCH.countDown(); }); } COUNT_DOWN_LATCH.await(); / / close the thread threadPoolExecutor. Shutdown (); }}Copy the code

Code like this: The number of core threads is 3, the maximum number of threads is 5, and the blocking queue is 20. A total of 50 threads are submitted. AbortPolicy is used for saturation policy here, analyzing the process of executing thread pool. So the thread pool adds tasks to the blocking queue, and it finds that the blocking queue still can’t hold 50 tasks, so it increases to 2 threads running tasks at the same time, so there are 5 threads running tasks at the same time, and 25 tasks in the thread pool will be executed and 25 tasks will be discarded. Because we are using AbortPolicy saturation policy, errors will be reported, as shown in the red line below. There were 25 missions. Other strategies you can follow.

How do you normally use thread pools?

  • Excutors. NewSingleThreadExecutor: 1 corePoolSize, LinkedBlockingQueue queue is infinite, while creating thousands of threads, queue infinite, OOM possible memory leak. Single thread.

  • Executors. NewCachedThreadPool: 0 corePoolSize, Interger. * * MAX_VALUE a maximum number of threads, * * when creating innumerable threads, OOM possible memory leak. Suitable for small and multi-threaded.

  • Executors. NewFixedThreadPool: n corePoolSize, maximum number of threads, n * * * * LinkedBlockingQueue blocking queue, when creating innumerable threads, queue infinite, OOM possible memory leak. Suitable for fixed threads.

  • Executors. NewScheduledThreadPool: n corePoolSize Interger. * * MAX_VALUE a maximum number of threads, * * when creating innumerable threads, OOM possible memory leak.

How do thread pools reuse threads in source code?

Each Worker is a thread. The number of Worker threads depends on the parameter. Each Worker takes data from the blocking queue in an infinite loop, and replaces the Runnable object in the Worker. Run its run method to the effect of thread replacement, the benefit of doing so is to avoid frequent thread switching multithreading, improve the performance of the program.

conclusion

Today we introduced several important aspects of the interview in the thread pool pilot, sort out the hope can help you, write than incomplete, at the same time there are many places that need to be corrected, I hope the pro to point out and comment, like please like and pay attention to oh. Point attention, do not get lost, I am called practice [public account], micro signal [jiaolian123ABC] while calling and practicing.