Home > Java > JavaInterview questions > Java interview thread pool

Java interview thread pool

王林
Release: 2020-12-17 10:12:28
forward
2315 people have browsed it

Java interview thread pool

The following are some common thread pool questions I have compiled in Java interviews, and I will share them with you now.

(Learning video sharing: java teaching video)

What is a thread pool?

Thread pool is a form of multi-thread processing. During the processing, tasks are submitted to the thread pool, and the execution of the task is managed by the thread pool.

If each request creates a thread to process, the server's resources will soon be exhausted. Using a thread pool can reduce the number of threads created and destroyed, and each worker thread can be reused. , can perform multiple tasks.

Why use thread pool?

The cost of creating and destroying threads is relatively large, and these times may be longer than the time of processing business. Such frequent creation and destruction of threads, coupled with business worker threads, consume system resource time, which may lead to insufficient system resources. (We can remove the process of creating and destroying threads)

What is the role of the thread pool?

The function of the thread pool is to limit the number of execution threads in the system.

1. Improve efficiency. Create a certain number of threads and put them in the pool, and take one from the pool when needed. This is much faster than creating a thread object when needed.

2. To facilitate management, you can write thread pool management code to manage the threads in the pool uniformly. For example, the program creates 100 threads when it is started. Whenever there is a request, a thread is assigned to work. , if there happen to be 101 concurrent requests, the extra request can be queued to avoid system crashes caused by endless thread creation.

Let’s talk about several common thread pools and usage scenarios

1. newSingleThreadExecutor

Create a single-threaded thread pool, which will only use the only working thread. Execute tasks to ensure that all tasks are executed in the specified order (FIFO, LIFO, priority).

2. newFixedThreadPool

Create a fixed-length thread pool that can control the maximum number of concurrent threads. Exceeding threads will wait in the queue.

3. newCachedThreadPool

Create a cacheable thread pool. If the length of the thread pool exceeds processing needs, idle threads can be flexibly recycled. If there is no recycling, create a new thread.

4. newScheduledThreadPool

Create a fixed-length thread pool to support scheduled and periodic task execution.

Several important parameters in the thread pool

corePoolSize is the number of core threads in the thread pool. These core threads will not be recycled only when they are no longer useful

maximumPoolSize is the maximum number of threads that can be accommodated in the thread pool

keepAliveTime is the longest time that other threads other than core threads can be retained in the thread pool, because in the thread pool, Except for core threads that cannot be cleared even when there are no tasks, the rest have a survival time, which means the longest idle time that non-core threads can retain

util is used to calculate this time one unit.

workQueue is a waiting queue. Tasks can be stored in the task queue waiting to be executed. The FIFIO principle (first in, first out) is implemented.

(More related interview question sharing: java interview questions and answers)

threadFactory is a thread factory that creates threads.

handler is a rejection strategy. We can refuse to perform certain tasks after the tasks are full.

Talk about the denial strategy of the thread pool

When request tasks continue to come and the system cannot handle them at this time, the strategy we need to adopt is to deny service. The RejectedExecutionHandler interface provides the opportunity for custom methods of rejecting task processing. Four processing strategies have been included in ThreadPoolExecutor.

AbortPolicy strategy: This strategy will directly throw an exception and prevent the system from working normally.

CallerRunsPolicy strategy: As long as the thread pool is not closed, this strategy runs the current discarded task directly in the caller thread.

DiscardOleddestPolicy strategy: This strategy will discard the oldest request, which is the task that is about to be executed, and try to submit the current task again.

DiscardPolicy strategy: This strategy silently discards tasks that cannot be processed without any processing.

In addition to the four rejection strategies provided by JDK by default, we can customize the rejection strategy according to our own business needs. The customization method is very simple, just implement the RejectedExecutionHandler interface directly.

What is the difference between execute and submit?

In the previous explanation, we used the execute method to execute tasks. In addition to the execute method, there is also a submit method that can also execute the tasks we submitted.

What is the difference between these two methods? In what scenarios are they applicable? Let's do a simple analysis.

execute is suitable for scenarios where you do not need to pay attention to the return value. You only need to throw the thread into the thread pool for execution.

The submit method is suitable for scenarios where you need to pay attention to the return value

Usage scenarios of five thread pools

newSingleThreadExecutor: A single-threaded thread pool that can be used in scenarios where sequential execution needs to be guaranteed, and only one thread is executing.

newFixedThreadPool: A fixed-size thread pool that can be used to limit the number of threads under known concurrency pressure.

newCachedThreadPool: A thread pool that can be expanded infinitely, which is more suitable for processing tasks with relatively small execution time.

newScheduledThreadPool: A thread pool that can be started with delay and scheduled, suitable for scenarios that require multiple background threads to perform periodic tasks.

newWorkStealingPool: A thread pool with multiple task queues, which can reduce the number of connections and create threads with the current number of available CPUs for parallel execution.

Close the thread pool

Closing the thread pool can be achieved by calling shutdownNow and shutdown methods

shutdownNow: issue interrupt() to all executing tasks and stop execution , cancel all tasks that have not yet started, and return the list of tasks that have not yet started.

shutdown: When we call shutdown, the thread pool will no longer accept new tasks, but it will not forcefully terminate tasks that have been submitted or are being executed.

Selection of the number of threads when initializing the thread pool

If the task is IO-intensive, generally the number of threads needs to be set to more than 2 times the number of CPUs to maximize the use of CPU resources.

If the task is CPU-intensive, generally the number of threads only needs to be set by adding 1 to the number of CPUs. More threads can only increase context switching but cannot increase CPU utilization.

The above is just a basic idea. If you really need precise control, you still need to observe the number of threads and queues in the thread pool after going online.

What kind of work queues are there in the thread pool?

1. ArrayBlockingQueue

is a bounded blocking queue based on an array structure. This queue is based on FIFO (first in first out) Principles to sort elements.

2. LinkedBlockingQueue

A blocking queue based on a linked list structure. This queue sorts elements according to FIFO (first in first out), and the throughput is usually higher than ArrayBlockingQueue. The static factory method Executors.newFixedThreadPool() uses this queue

3, SynchronousQueue

a blocking queue that does not store elements. Each insertion operation must wait until another thread calls the removal operation, otherwise the insertion operation will always be blocked, and the throughput is usually higher than the LinkedBlockingQueue. The static factory method Executors.newCachedThreadPool uses this queue.

4. PriorityBlockingQueue

An infinite blocking queue with priority.

Related course recommendations: java introductory tutorial

The above is the detailed content of Java interview thread pool. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template