In work, threads are often involved. For example, some tasks, often hand and thread to execute asynchronously. or the server-side program creates a separate thread-handling task for each request. threads, such as the database connection we use. These create destruction or turn on closed operations, which greatly affect system performance. So, the usefulness of the "pool" is highlighted.
1. Why use a thread pool
In the implementation method described in section 3.6.1, a new worker thread is assigned to each customer. When the worker thread communicates with the customer, the thread is destroyed. This implementation has the following deficiencies:
• The cost of server creation and destruction work, including the time spent and system resources, is large. This does not need to explain, you can check the "thread creation process." In addition to the work done by the machine itself, we have to instantiate, start, all of which need to occupy the stack resources.
• The active thread consumes system resources in addition to the overhead of creating and destroying threads. This should be the consumption of stack resources, guess the number of database connections set a reasonable value, also have this consideration.
• Thread switching is relatively fixed if the number of threads is fixed and each thread has a long declaration cycle. Different operating systems have different switching cycles, generally around 20ms. This is said to switch between the JVM and the underlying operating system under the schedule, the thread transfer CPU between the right to use. If you frequently create and destroy threads, you will frequently switch threads, because after a thread is destroyed, it is necessary to give up the right to the already ready thread, so that the thread to get the opportunity to run. In this case, the switch between threads does not follow the fixed switching cycle of the system, and the cost of switching threads is even greater than the cost of creating and destroying them.
By contrast, using a thread pool, you can create threads that are constantly fetching tasks from the work queue and then performing the task. When a worker thread finishes a task, it continues to perform another task in the work queue. The advantages are as follows:
• Reduce the number of creation and destruction times, and each worker thread can be reused and can perform multiple tasks.
• The number of threads in the thread pool can be easily adjusted according to the load capacity of the system, preventing the system from collapsing because of excessive system resources consumption.
2. The simple realization of thread pool
The following is a simple thread pool written by yourself, which is also directly tapped from the book on Java Network programming.
Package thread;
Import java.util.LinkedList; /** * thread pool implementation, according to the length of the regular thread pool, the maximum length, queue length, we can increase the number of restrictions to achieve * @author Han/public class Mythreadpool extends threadgroup{//cpu
Quantity---runtime.getruntime (). Availableprocessors ();
Whether to close private Boolean isclosed = false;
Queue private linkedlist<runnable> Workqueue;
Thread pool ID private static int threadpoolid;
private int ThreadID; Public mythreadpool (int poolsize) {super ("Mythreadpool.")
+threadpoolid);
threadpoolid++;
Setdaemon (TRUE);
Workqueue = new linkedlist<runnable> ();
for (int i = 0;i<poolsize;i++) {new Workthread (). Start (); }//This can be replaced by concurrentlinkedqueue, you can avoid the use of synchronized efficiency issues public synchronized void execute (Runnable task) {if (i
sclosed) {throw new IllegalStateException ("Connection pool is closed ...");
}else{Workqueue.add (Task);
Notify ();
} protected synchronized Runnable 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 ();
The public void join () {synchronized () {isclosed = true;
Notifyall ();
} thread[] Threads = new Thread[activecount ()];
int count = enumerate (threads);
for (int i = 0;i<count;i++) {try {threads[i].join (); Workthread extends thread{public workthread () {super (MYTHR) for catch (Exception e) {}}}
Eadpool.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 ();
The catch (Exception e) {} if (Task!= null) { Task.run ();
}else{break; }
}
}
}
}
The thread pool primarily defines a task Force column and some prebuilt threads. You can submit a task to a thread whenever you call the Execute method.
The back thread blocks at Gettask () when there is no task, until a new task comes in to be awakened.
Both join and close can be used to turn off the thread pool. The difference is that the join finishes the task in the queue, while close clears the queue and interrupts all the worker threads. The interrupt () in close () is the equivalent of calling the respective interrupt () of the threadgroup containing the child thread, so the thread throws the interruptexception when it is in wait or sleep.
The test classes are 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 the 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 pooling implementation that is more robust, efficient, and more powerful than our own implementations.
The class diagram is as follows:
For this type of thread pool, the predecessors have a good explanation. Arbitrary Baidu under the Java thread pool, have written a very detailed examples and tutorials, here is no longer to repeat.
4. Spring Injection thread pool
When using the spring framework, if we create a thread pool with Java-provided methods, it is very inconvenient to manage in multithreaded applications and does not conform to our idea of using spring. (although spring can be injected through static methods)
In fact, spring itself provides a good thread pool implementation. 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}"/>
<!--thread pool maintain minimum number of threads-->
< Property Name= "Keepaliveseconds" value= "${threadpool.keepaliveseconds}"/>
<!--thread pool to maintain the idle time allowed by the thread-->
<property name= "maxpoolsize" value= "${threadpool.maxpoolsize}"/>
<!--thread pool maintain maximum number of threads-->
<property name= The buffer queues used by the "queuecapacity" value= "${threadpool.queuecapacity}"/>
<!--thread pool-->
< /bean>
5. Considerations for using Thread pooling
• Deadlock
Any multithreaded program has the risk of deadlock, the simplest case is two threads Ab,a hold lock 1, request lock 2,b hold lock 2, request lock 1. (This situation in the MySQL exclusive lock will also appear, not the database will be directly error prompts). There is another deadlock in the thread pool: Assuming that all worker threads in the thread pool are blocked while performing their respective tasks, they are waiting for the result of the execution of a task A. Task A is in the queue and cannot be executed because there are no idle threads. All the resources of the thread pool will be blocked and the deadlock will occur.
• Insufficient system resources
If there are a very large number of threads in the thread pool, these threads consume a significant amount of resources, including memory and other system resources, which can severely affect system performance.
• Concurrency error
The work queue of the thread pool relies on the wait () and notify () methods to make the worker thread get the task in time, but the two methods are difficult to use. If the code is wrong, the notification may be lost, causing the worker thread to remain idle, ignoring the task that needs to be handled in the work queue. Because it's best to use some of the more mature thread pools.
• Thread leaks
One serious risk of using the thread pool is a thread leak. For thread pools with a fixed number of worker threads, if the worker thread throws runtimeexception or errors when it executes the task, and the exception or error is not captured, the worker thread terminates abnormally, causing the line Chengtiyongju to lose a thread. (This is too interesting)
Alternatively, the worker thread is blocked while executing a task, and the thread is blocked if it waits for the user's input data, but the user does not enter data at all. Such a worker thread does not exist, and it does not actually perform any tasks. If all the threads in the thread pool are in this state, the thread pool will not be able to join the new task.
• Task overload
These tasks themselves may consume too much system resources and cause resource shortages when there are a large number of queued tasks in the worker thread queue.
To sum up, use the thread pool to follow the following guidelines:
1. Task A is not appropriate to join a work queue in the thread pool if task a needs to synchronize the execution results of task B while it is in progress. If you put the same as task A to wait for the results of other tasks to join in the queue, may cause deadlock
2. If a task can be blocked and is blocked for a long time, the timeout should be set to avoid a thread leaking because the worker thread is permanently blocked. In the server-only program, when a thread waits for a client to connect, or waits for the data that the customer sends, it can cause blocking, and it is possible to set the time in the following ways:
Call the ServerSocket Setsotimeout method to set the timeout for waiting for a client connection.
For each socket that is connected to the customer, call the Setsotimeout method of the socket and set the timeout for waiting for the customer to send the data.
3. Understand the characteristics of the task, the analysis task is to perform frequently blocking IO operations, or to perform operations that are not blocked. The former is a time consuming CPU, while the latter has a higher utilization rate. Estimated how long it will take to complete the task, is a short time task or long time task, and then according to the characteristics of the task, the task classification, and then the different types of tasks to join the different thread pool work queue, so that according to the characteristics of the task, the allocation of adjustment of each thread pool
4. Adjust the size of the thread pool. The optimal size of the thread pool depends largely on the number of available CPUs in the system and the characteristics of the tasks in the work queue. If there is only one Task Force column on a system with n CPUs and all of them are operational (not blocked) tasks, the maximum CPU usage is generally achieved when the thread pool has n or n+1 worker threads.
If the work queue contains tasks that perform IO and are often blocked, make the thread pool larger than the available CPUs because not all worker threads are working. Select a typical task, and then estimate that in the project in which the task is performed, the wait time is wt/st the proportion of the time it actually takes to compute the CPU. For a system with n CPUs, it is necessary to set approximately n (1+wt/st) threads to ensure that the CPU is fully utilized.
Of course, CPU utilization is not the only thing to consider in adjusting the thread pool, and as the number of thread pools grows, there are limits to memory or other resources, such as sockets, open file handles, or number of database connections. To ensure that multithreaded consumption of the system resources within the system to withstand the scope.
5. Avoid overload of tasks. The server should limit the number of concurrent connections to the client, depending on the system's load capacity. When a customer's connection exceeds the limit, the server can reject the connection and make friendly hints, or limit the queue length.
The above Java thread pool of several implementation methods and FAQs are small parts to share all the content, hope to give you a reference, but also hope that we support the cloud-dwelling community.