Many developers talk about Java multithreaded development, just stay on the new thread (...). Start () or directly using the executor framework, for thread management and control is not deep enough, read "Java Concurrency Programming practice" to learn a lot of things that are not known to me but very important details, today collation as follows.
Disadvantages of not applying a thread pool
Some developers take the hassle out of the need for multi-threading, the direct new thread (...). Start () is not a problem for general scenarios, but if it is a high number of concurrent requests, there are some pitfalls:
-
The cost of the new thread. Threads are a lot lighter than processes, but for the JVM, the cost of creating a new thread is quite large, unlike creating a new object
-
Resource consumption. Without a pool to limit the number of threads, the number of threads will directly depend on the concurrency of the application, so there is a huge potential for thread data, so resource consumption will be huge
-
Stability. Stability can be problematic when the number of threads exceeds the level of system resources
Develop an execution strategy
In every place where multi-threading is required, regardless of how large the concurrency is, you need to consider the execution strategy of the thread
-
The order in which the tasks are executed
-
can have any number of concurrent executions
-
How many tasks can go into waiting for the execution queue
-
What tasks should I give up when the system is overloaded? How do I notify the application?
-
What should be done before and after a task is executed
Type of thread pool
Whether you create a thread pool through executors or manage it through spring, you need to know exactly what kinds of thread pools are available:
-
Fixedthreadpool: Thread pool, which creates threads at the time of submission of the task, until the maximum capacity of the pool, if the thread is not expected to end, will replenish the new threads
-
Cachedthreadpool: Variable thread pool, which is like a spring, if there is no task requirement, it reclaims the idle thread, if the demand increases, increase the thread on demand, do not limit the size of the pool
-
Singlethreadexecutor: Single Thread. Tasks that cannot be processed go into the FIFO queue and wait for execution.
-
Secheduledthreadpool: A recurring thread pool. Support for performing recurring thread tasks
In fact, these different types of thread pools are done by building a threadpoolexecutor, the difference is corepoolsize,maximumpoolsize,keepalivetime,unit,workqueue, Threadfactory so many parameters. Refer to JDK DOC for details.
Thread pool saturation Policy
By the type of on-line pool, in addition to cachedthreadpool other thread pool has saturation, when saturated will require the corresponding policy to process the task of the request thread, Threadpoolexecutor take the way through the queue to store these tasks, Of course, different queues are selected depending on the type of pool, such as Fixedthreadpool and Singlethreadexecutor, which use an infinite length of linkedblockingqueue by default. But in terms of system controllability, the best practice is to use fixed-length arrayblockingqueue or limited linkedblockingqueue, And when the time limit is reached by Threadpoolexecutor.setrejectedexecutionhandler method to set a policy for rejecting a task, the JDK provides AbortPolicy, Callerrunspolicy, Discardpolicy, discardoldestpolicy Several strategies, specific differences visible JDK DOC
Thread has no dependencies
Multi-threaded task design as far as possible to make the tasks are independent, so-called dependency can be two aspects:
-
dependencies between threads. If a thread has dependencies it can cause deadlocks or starvation
-
The caller-to-thread dependency. The caller has to monitor the completion of the thread to affect the amount of concurrency
Of course, in some businesses do need certain dependencies, such as the caller needs to get the thread to complete the result, the traditional thread is inconvenient to complete, because the Run method has no return value, only through some shared variables to pass the result, But in the executor framework you can implement tasks that require a return value through the future and the callable, and of course the asynchronous nature of the thread leads to the need for a mechanism to ensure that the caller can wait for the task to be completed, and the usage of the future and the callable is seen at a glance:
Public class futurerenderer { private final executorservice executor = ...; void renderpage (Charsequence source) { final list<imageinfo> imageinfos = scanforimageinfo (source); Callable<List<ImageData>> task = new callable<list <ImageData>> () { public list<imagedata> call () { list<imagedata> result = new ArrayList<ImageData> (); for (Imageinfo imageinfo : imageinfos) result.add (Imageinfo.downloadimage ()); return result; } }; &nbsP; future<list<imagedata>> future = executor.submit ( Task); rendertext (source); try { List< Imagedata> imagedata = future.get (); for (Imagedata data : imagedata) renderimage (data); } catch (interruptedexception e) { // re-assert the thread ' s interrupted Status thread.currentthread (). Interrupt (); &nbSp; // we don ' t need the result, so cancel the task too Future.cancel (True); } catch (ExecutionException e) { throw Launderthrowable (E.getcause ()); } }}
The key of the above code is list<imagedata> ImageData = future.get (); If the callable type of task is not finished, the caller will block the wait. However, this is a way to use caution, it is easy to create bad design. In addition to this need to wait for the scene, you need to set a maximum tolerance time timeout, the setting method can be future.get () plus the timeout parameter, or re-call Executorservice.invokeall Plus timeout parameter
cancellation and shutdown of threads
In general, the thread is closed after it has been run, but sometimes it is canceled or closed, such as the following:
-
The caller forcibly cancels. For example, a long-running task, the user clicks the "Cancel" button to forcibly cancel
-
Time-limited tasks
-
Non-processed tasks occur
-
Shutdown of the entire application or service
Therefore, there is a need to have appropriate methods and policies for canceling or shutting down to control threads, generally the following methods:
1) Control by variable identification
This approach is old-fashioned, but widely used, and the main drawback is that there is no good control over blocked operations, as shown in the following code:
public class primegenerator implements runnable { @ Guardedby ("This") private final list<biginteger> primes = new ArrayList< Biginteger> (); private volatile boolean cancelled; public void run () { biginteger p = biginteger.one; while (!cancelled ) { p = p.nextprobableprime (); synchronized (This) { prImes.add (P); } } } public Void cancel () { cancelled = true; } public synchronized list<biginteger> get () { return new ArrayList<BigInteger> (primes); }}
2) Interrupt
Interrupts are usually the wisest choice to implement cancellation, but the thread itself needs to support interrupt handling, and to handle the interrupt policy, there are generally two ways to respond to interrupts:
3) Cancel non-interruptible blocking
There are some non-disruptive blockages, such as:
The cancellation of these threads requires a specific case-specific treatment, such as for socket blocking, and if you want to safely cancel, you need to call Socket.close ()
4) Shutdown of the JVM
If a task needs to do some cleanup before the JVM shuts down, instead of being hardened by the JVM, you can use the JVM's hook technology, and the JVM hooks are just a common technique, which is to use a map to save some tasks that need to be started before the JVM shuts down. These task threads are started concurrently during a session of the JVM shutdown process. Examples of specific use are:
public void Start () {Runtime.getruntime (). Addshutdownhook (New Thread () {public void run () {try {L OgService.this.stop (); } catch (Interruptedexception ignored) {}}});
Java Multithreading Development Tips