Java thread pool implementation and FAQs
Threads are often involved in work. For example, some tasks are often handed in to threads for asynchronous execution. Or the server program creates a separate thread processing task for each request. Outside the thread, such as the database connection we use. These operations can be created, destroyed, or disabled, which greatly affects system performance. Therefore, the usefulness of the "pool" is highlighted.
1. Why use the thread pool?
In the implementation method described in section 3.6.1, a new working thread is assigned to each customer. When the communication between the worker thread and the customer ends, the thread is destroyed. This implementation method has the following shortcomings:
- The cost of server creation and destruction (including the time and system resources consumed) is high. This does not need to be explained. You can check the "thread creation process ". In addition to the work done by the machine itself, we also need to instantiate and start, all of which need to occupy stack resources.
- In addition to the overhead of creating and destroying threads, active threads also consume system resources. This should be the consumption of stack resources. This is also a consideration for setting a reasonable value for guessing the number of database connections.
- If the number of threads is fixed and each thread has a long Declaration cycle, thread switching is also relatively fixed. Different operating systems have different switching cycles, generally around 20 ms. The switch here refers to the transfer of cpu usage between threads under the scheduling of jvm and the underlying operating system. If a thread is frequently created and destroyed, the thread will be frequently switched. After a thread is destroyed, the right to use it must be granted to the ready thread to give the thread a running opportunity. In this case, the switching between threads does not follow the fixed switching cycle of the system. the overhead of switching threads is even greater than that of creating and destroying threads.
Relatively speaking, when a thread pool is used, some threads are pre-created. They constantly extract tasks from the work queue and then execute the tasks. After a worker thread executes a task, it continues to execute another task in the work queue. Advantages:
- This reduces the number of times of creation and destruction. Each worker thread can be reused and multiple tasks can be executed.
- The number of threads in the thread pool can be easily adjusted based on the system's load capacity to prevent system crashes due to excessive consumption of system resources.
2. Simple implementation of Thread Pool
The following is a simple thread pool written by myself, which is also produced directly from the Java Network Programming book.
Package thread; import java. util. implementation list;/*** thread pool implementation. Based on the length, maximum length, and queue length of the conventional thread pool, we can increase the number limit to implement * @ author Han */public class MyThreadPool extends ThreadGroup {// Number of CPUs --- Runtime. getRuntime (). availableProcessors (); // whether to disable private boolean isClosed = false; // queue private queue list <Runnable> workQueue; // thread pool id private static int threadPoolID; private int threadID; public MyThreadPool (int poolSize) {super ("M YThreadPool. "+ threadPoolID); threadPoolID ++; setDaemon (true); workQueue = new queue list <Runnable> (); for (int I = 0; I <poolSize; I ++) {new WorkThread (). start () ;}// you can replace concurrent1_queue here to avoid the efficiency problem of synchronized. public synchronized void execute (Runnable task) {if (isClosed) {throw new IllegalStateException ("the connection pool has been closed... ");} else {workQueue. add (task); y () ;}} protected synchronized Runnabl E getTask () throws InterruptedException {while (workQueue. size () = 0) {if (isClosed) {return null;} wait ();} return workQueue. removeFirst ();} public synchronized void close () {if (! IsClosed) {isClosed = true; workQueue. clear (); interrupt () ;}} public void join () {synchronized (this) {isClosed = true; policyall ();} thread [] threads = new Thread [activeCount ()]; int count = enumerate (threads); for (int I = 0; I <count; I ++) {try {threads [I]. join () ;}catch (Exception e) {}} class WorkThread extends Thread {public WorkThread () {super (MyThreadPool. this, "workThread" + (threadID ++ ); System. out. println ("create...") ;}@ Override public void run () {while (! IsInterrupted () {System. out. println ("run .. "); Runnable task = null; try {// This is a blocking method task = getTask ();} catch (Exception e) {} if (task! = Null) {task. run () ;}else {break ;}}}}}
This thread pool mainly defines a work queue and some pre-created threads. You can submit a task to the thread by calling the execute method.
When the following thread does not have a task, it will be blocked in getTask () until a new task comes in and is awakened.
Both join and close can be used to close the thread pool. The difference is that join will finish the tasks in the queue, and close will immediately clear the queue and interrupt all working threads. Interrupt () in close () is equivalent to calling the respective interrupt () of ThreadGroup containing sub-threads. Therefore, InterruptException is thrown when a thread is in wait or sleep state.
The test class is as follows:
public class TestMyThreadPool { public static void main(String[] args) throws InterruptedException { MyThreadPool pool = new MyThreadPool(3); for(int i = 0;i<10;i++){ pool.execute(new Runnable() { @Override public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) { } System.out.println("working..."); } }); } pool.join(); //pool.close(); }}
3. The thread pool provided by the jdk class library
Java provides a good thread pool implementation, which is more robust and efficient than our own implementation and has more powerful functions.
The class diagram is as follows:
Our predecessors have provided a good explanation of this type of thread pool. Any java thread pool under Baidu has written very detailed examples and tutorials, which will not be described here.
Java built-in thread pool and queue details
4. spring injection Thread Pool
When using the spring framework, if we use the method provided by java to create a thread pool, it is inconvenient to manage the thread pool in multi-threaded applications and does not conform to the idea of using spring. (Although spring can be injected using static methods)
In fact, Spring also provides a good implementation of the thread pool. This class is called ThreadPoolTaskExecutor.
The configuration in spring is as follows:
<Bean id = "executorService" class = "org. springframework. scheduling. concurrent. threadPoolTaskExecutor "> <property name =" corePoolSize "value =" $ {threadpool. corePoolSize} "/> <! -- Minimum number of threads maintained by the thread pool --> <property name = "keepAliveSeconds" value = "$ {threadpool. keepAliveSeconds}"/> <! -- Idle time allowed by the thread pool maintenance thread --> <property name = "maxPoolSize" value = "$ {threadpool. maxPoolSize}"/> <! -- Maximum number of threads maintained by the thread pool --> <property name = "queueCapacity" value = "$ {threadpool. queueCapacity}"/> <! -- Buffer Queue used by the thread pool --> </bean>
5. Considerations for using the thread pool
Any multi-threaded program has the risk of deadlock. The simplest case is that two threads AB, A hold lock 1, request lock 2, B hold lock 2, and request lock 1. (In this case, the exclusive lock of mysql will also appear, and the database will not directly report an error ). There is another deadlock in the thread pool: Assuming that all worker threads in the thread pool are blocked when they are executing their respective tasks, they are waiting for the execution result of A job. Task A is in the queue and cannot be executed because there is no idle thread. In this way, all resources in the thread pool will be congested and deadlocks will occur.
- Insufficient system resources
If the thread pool contains a large number of threads, these threads consume a large amount of resources, including memory and other system resources, seriously affecting system performance.
The working queue of the thread pool relies on the wait () and Y () methods to make the working thread obtain the task in time, but these two methods are difficult to use. If the code is incorrect, the notification may be lost, causing the working thread to remain idle and ignoring the tasks to be processed in the working queue. Because it is best to use some mature thread pools.
A major risk of using the thread pool is thread leakage. For a thread pool with a fixed number of worker threads, if the worker thread throws RuntimeException or Error during task execution and these exceptions or errors are not captured, the worker thread terminates unexpectedly, this causes the thread pool to lose a thread permanently. (This is too interesting)
Another case is that the worker thread is blocked when a task is executed. If the user waits for the user's input data but the user does not input the data, the thread is blocked all the time. This kind of working thread name actually exists, and it does not actually execute any task. If all threads in the thread pool are in this status, the thread pool cannot be added to new tasks.
When a worker thread queue contains a large number of tasks waiting for execution, these tasks may consume too much system resources and cause resource shortage.
To sum up, the following principles should be observed when using a thread pool:
Classification: Java Network Programming label: Thread Pool