Summary of Java thread pool concepts (thread pool)

1. Application of pooling idea

Pooling idea is a common software design and optimization technology. The following are several common application scenarios of pooling ideas:

  1. Thread pool: Thread pool is a typical application of pooling idea. Reusing threads reduces the overhead of thread creation and destruction and improves system performance and responsiveness by pre-creating a set of threads and placing them in a ready state.

  2. Connection pool: Connection pool is a common application in database and network programming. Improve the efficiency of database access and network communication by creating a batch of database connections or network connections in advance and putting them in a reusable state to avoid frequent creation and release of connections.

  3. Object pool: Object pool is used to manage and reuse reusable objects. For example, database connection pool, thread-safe cache pool, etc. Through the object pool, you can avoid frequent creation and destruction of objects and improve system performance and resource utilization.

  4. Memory pool: Frequent memory allocation and release may cause memory fragmentation and reduce memory utilization efficiency. The memory pool divides a contiguous memory space into fixed-size blocks and maintains a list of free blocks. Programs can apply for and release memory blocks from the memory pool to reduce memory fragmentation and improve memory allocation performance.

  5. String pool: String pool reduces memory usage and increases the speed of string comparison by sharing the same strings in a pool. The string constant pool in Java is a typical string pool application.

        The application of these pooling ideas is aimed at improving system performance, resource utilization and development efficiency, avoiding repeated creation and destruction of objects, thereby reducing system overhead and providing a better user experience.

2. Working principle of thread pool

The working principle of the thread pool can be basically divided into the following steps:

  1. Initialize the thread pool: Create a thread pool manager and set the thread pool parameters, including the number of threads, work queue size, etc.

  2. Create threads: Based on the initial configuration of the thread pool, create a specified number of threads and put them in a ready state waiting to execute tasks.

  3. Receiving tasks: When there is a task that needs to be executed, the thread pool will receive it and queue it for processing. Tasks can be objects that implement the Runnable interface or the Callable interface.

  4. Task scheduling: Threads in the thread pool obtain tasks from the work queue and select them according to the preset scheduling strategy, such as first-in-first-out (FIFO), least recently used (LRU), etc.

  5. Execute the task: The selected thread will take out the task from the work queue and execute the run() or call() method of the task. After the task is executed, the thread enters the idle state and waits for the next task.

  6. Thread recycling: When the thread pool has been idle for a period of time, the manager may decide to destroy some threads to save system resources. After the thread is destroyed, the number of threads in the thread pool will be reduced accordingly.

  7. Error handling: The thread pool will capture exceptions generated during task execution to prevent threads from crashing due to uncaught exceptions. Exception handling strategies can be customized according to specific needs, such as re-executing, logging, ignoring, etc.

        Through the above working principles, the thread pool realizes thread reuse and rational utilization of resources, allowing the system to better handle concurrent tasks and improve performance and response speed. At the same time, the thread pool can also control the number of threads to avoid resource consumption and performance degradation caused by too many threads, and provide a thread management mechanism.

3. Briefly describe your understanding of thread pools

       If you are asked this question, you can expand on how to use the thread pool, the benefits of the thread pool, and the startup strategy of the thread pool. Proper use of the thread pool can bring three benefits.
        First: Reduce resource consumption. Reduce the cost of thread creation and destruction by reusing created threads.
        Second: Improve response speed. When a task arrives, the task can be executed immediately without waiting for the thread to be created.
        Third: Improve thread manageability. Threads are scarce resources. If they are created without restrictions, they will not only consume system resources, but also reduce the stability of the system. The thread pool can be used for unified allocation, tuning and monitoring.

        A thread pool is a mechanism for managing and reusing threads. It consists of a thread pool manager, work queue and a set of threads. The thread pool manager is responsible for creating, destroying and monitoring threads in the thread pool. It dynamically adjusts the number of threads based on system load and preset conditions to ensure efficient utilization and reasonable allocation of the thread pool. Work queues are used to store pending tasks. Threads in the thread pool take tasks from the work queue and execute them. When the number of tasks exceeds the processing capacity of the thread pool, the tasks will be temporarily placed in the queue and will be processed when there are idle threads.

Are the more threads the better?

  1. A thread is an object in Java, and it is also a resource of the operating system. It takes time to create and destroy threads. If creation time + meeting time > task execution time, it is very uneconomical.
  2. Java objects occupy heap memory, and operating system threads occupy system memory. According to the JVM specification, the default maximum stack size of a thread is 1M. This stack space needs to be allocated from system memory. Too many threads will consume a lot of memory.
  3. The operating system needs to frequently switch thread contexts (each thread wants to be run), which affects performance.

The thread pool was introduced to facilitate the control of the number of threads.

        When using a thread pool, you need to consider factors such as the number of threads, work queue size, and task scheduling strategy to ensure that the thread pool works as expected and provides optimal performance. At the same time, we must also pay attention to handling exceptions to prevent threads from crashing the entire thread pool due to uncaught exceptions.

Why is it not recommended to use Executors static factory to build thread pool?

        Alibaba Java Development Manual clearly states that it is not allowed to use Executors static factories to build thread pools for the following reasons:
Thread pools are not allowed to be created using Executors, but through ThreadPoolExecutor. This processing method makes the writing students more clear about the thread pool. Run rules to avoid the risk of resource exhaustion. Note: The disadvantages of the thread pool object returned by Executors are as follows:

1: FixedThreadPool and SingleThreadPool:
The allowed request queue (the underlying implementation is LinkedBlockingQueue) length is Integer.MAX_VALUE, which may accumulate a large number of requests, resulting in OOM
2:
The number of threads allowed to be created by CachedThreadPool and ScheduledThreadPool is Integer.MAX_VALUE, which may be created A large number of threads, leading to OOM.

        The correct posture for creating a thread pool: avoid using Executors to create a thread pool, mainly to avoid using the default implementation, then we can directly call the constructor of ThreadPoolExecutor to create the thread pool ourselves. When creating, just specify the capacity for BlockQueue.

private static ExecutorService executor=newThreadPoolExecutor(10,10,60L,TimeUnit.SECONDS,new ArrayBlockingQueue(10));

Or use open source libraries: open source libraries, such as apache and guava.

How does the thread pool know that a thread task has been completed?

        Thread pools usually use a mechanism called "Future" to track the execution status of thread tasks.

        In Java, java.util.concurrent.Futurethe results of asynchronous calculations can be represented through interfaces. Tasks submitted by the thread pool can return a Future object. After the task execution is completed, the execution result of the task can be obtained through this object or whether the task is completed.

Specifically, you can use Future to know whether the thread task has been completed by following the following steps:

  1. Submit the task: Submit the task to be executed to the thread pool and obtain the returned Future object.

  2. Determine task status: Determine whether the task has been completed by calling the Future isDone()method. Returns true if the task is completed; otherwise returns false.

  3. get()Get task results: If the task has been completed, you can get the task execution results by calling the Future method. This method blocks the current thread until the task is completed and the results are returned.

        It should be noted that if the task has not been completed, calling get()the method will block the current thread until the task execution is completed. If you do not want to block the current thread, you can use isDone()method polling to determine the task status, or use a method with a timeout parameter get()to wait for a period of time to obtain the result.

        In short, by using Future objects, the thread pool can easily track and obtain the execution status and results of thread tasks, thereby achieving management and control of tasks.

reference:

7 ways to create a thread pool in Java! - Brother Lei|www.javacn.site - Blog Park (cnblogs.com)

Java thread pool implementation principle and its practice in Meituan business - Meituan technical team (meituan.com)

JUC thread pool: Detailed explanation of ThreadPoolExecutor | Java full stack knowledge system (pdai.tech)

Thread pool interview questions - Xiaoyuren - Blog Park (cnblogs.com)

Guess you like

Origin blog.csdn.net/weixin_49171365/article/details/129570630