Use of Java concurrent programming Thread Pool
Implicit coupling between tasks and execution policies
The Executor framework can decouple the submission of tasks from the execution policies of tasks (that is, independence ). Although the Executor framework provides considerable flexibility for developing and modifying execution policies, not all tasks can apply all execution policies.
For example:
Dependency task
For example, if the task depends on the execution time sequence, execution result, or other effects, the task is implicitly dependent. In this case, you must maintain these execution policies with caution to avoid active issues (such as deadlocks that cause difficult execution issues)
Tasks using the thread-closed Mechanism
Compared with the thread pool, single-threaded executors can make stronger commitments to concurrency, ensuring that tasks are not executed concurrently.
Tasks that are sensitive to response time
For example, GUI tasks. If you submit a task that has been running for a long time to the Executor of a single thread. Or, if you submit multiple tasks that have been running for a long time to a thread pool that contains only a few threads, the Executor's responsiveness will be reduced.
Use ThreadLocal tasks
ThreadLocal enables each thread to have a private version of a variable, however. As long as the conditions allow Executor to freely reuse these threads. In the standard Executor, space threads will be reclaimed when the execution demand is low, and new threads will be added when the demand increases, and if an unchecked exception is recruited from the task, A new thread will be used to replace the problematic thread. It is meaningful to use ThreadLocal in the thread pool only when the life cycle of the local value of the thread is limited by the life cycle of the task, in the thread pool, Threadlocal should not be used to pass values between tasks.
Finally, the performance of the thread pool can be optimal only when tasks of the same type are independent of each other. If you place tasks with a large difference in running time in the same thread pool, the thread pool will be blocked unless the thread pool is large enough .. In typical network-based server applications, such as web servers, email servers, and file servers, their requests are of the same type and independent of each other.
Remember to write your execution policy into the document. In the future, maintenance personnel will not use wrong execution policies to undermine security and activity.
Thread hunger deadlock
For single-threaded Executor. If two tasks are submitted, and the two tasks depend on each other's execution results, a deadlock will occur.
Example:
Import java. lang. processBuilder. redirect; import java. util. concurrent. callable; import java. util. concurrent. executorService; import java. util. concurrent. executors; import java. util. concurrent. future; public class ThreadDeadlock {ExecutorService exec = Executors. newSingleThreadExecutor (); public static void main (String [] args) {try {ThreadDeadlock tdl = new ThreadDeadlock (); System. out. println (tdl. new ReaderPageTask (). call ();} catch (Exception e) {// TODO Auto-generated catch blocke. printStackTrace () ;}} public class ReaderPageTask implements Callable
{@ Overridepublic String call () throws Exception {// TODO Auto-generated method stubFuture
Header, footer; header = exec. submit (new LoadFileTask ("header.html"); footer = exec. submit (new LoadFileTask ("footer.html"); String page = "bodyyyyyyyyyyyyyyy"; // deadlock will occur because the task is waiting for the result return header of the subtask. get () + page + footer. get () ;}} public class LoadFileTask implements Callable
{Public LoadFileTask (String filepath) {super (); // TODO Auto-generated constructor stub} @ Overridepublic String call () throws Exception {// TODO Auto-generated method stubreturn "sdf ";}}}
The preceding chestnuts can be computed. However, it is much slower. It is a deadlock caused by thread hunger.
Deadlocks do not have to be "dead". Let's take a look at the definition of deadlocks.
Standard Definition of deadlock: every process in the set is waiting for an event that can only be triggered by other processes in the set, then the process in this group is deadlocked.
In addition to explicit restrictions on the thread pool size, there are also many deadlocks caused by external resource restrictions. For example, if the jdbc limit has 10 connections, each thread needs a connection, there are already 10 threads running in the thread pool, so although the next thread is already in the thread pool, it is blocked because it cannot connect to the database.
Tasks with long running time
If the task is blocked for too long, the responsiveness of the thread pool will become worse even if no deadlock occurs. Java has already prepared a solution to the problem. In most blocking methods, java libraries have a limited-time version and an unlimited version, such as Thread. join. Blockingqueue. put. CountDownLatch. await and Select. select. If the wait times out, you can identify the task as a failure, stop the task, or put the task back into the queue, or even add a counter. If the failure persists several times, stop it. If the thread pool is always filled with blocked tasks, it may also indicate that the thread pool is too small.
The following example shows the meaning of Thread. join (timeout ).
public class ThreadDeadlock {public Boolean flag = false;public static void main(String[] args) {testThread tt = new ThreadDeadlock().new testThread();testThread1 tt1 = new ThreadDeadlock().new testThread1();tt1.start();try {tt1.join(200);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}tt.start();}class testThread extends Thread {@Overridepublic void run() {int result = 0;// TODO Auto-generated method stubwhile (true)System.out.println(result);}}class testThread1 extends Thread {@Overridepublic void run() {int result = 10;while (true)System.out.println(result);}}}
The result is. First, 10 of 200 milliseconds are output, and then 0 is output. That is to say, the join timeout mechanism is the task of the thread that executes the Join first, so that it can be completed first. However, if the task cannot be completed within this time period after the timeout is set, the blocking will be abandoned. Execute the following tasks concurrently