The use of thread pool for Java concurrent Programming (ii)

Source: Internet
Author: User

Set the size of the thread pool

If the thread pool is too large, resources may be exhausted and if it is too small, many idle processors will not work, thereby reducing throughput.


To set the correct thread pool size, you need to analyze the computing environment, the nature of the resource budget and tasks, the number of CPUs, the size of the memory, whether the task is computationally intensive or I/O intensive, or both. Whether they need scarce resources like JDBC connections, here's a formula for calculating

N (threads) =n (CPU) *u (CPU) * (1+W/C);

N (threads) is the last resulting size.

N (CPU) is the number of CPUs, my computer is a dual core four threads, the number of CPUs will be 4, can be through System.out.println (Runtime.getruntime (). Availableprocessors ()); To get the number of CPUs

The u (cpu) is the target CPU usage, depending on the programmer's expectations, typically around 50%. This value is limited to between 0 and 1

W/C is the ratio of wait time/compute time.

Configure Threadpoolexecutor

Threadpoolexecutor provides basic implementations for some executor, such as Newcachedthreadpool,newfixedthreadpool and so on. Threadpoolexecutor allows a variety of custom

Its constructor is as follows

    Public threadpoolexecutor (int corepoolsize,                              int maximumpoolsize,                              long KeepAliveTime,                              timeunit Unit,                              blockingqueue<runnable> WorkQueue,                              Threadfactory threadfactory,                              Rejectedexecutionhandler handler) {}
Our most commonly used newcachedthreadpool.

  public static Executorservice Newcachedthreadpool () {        return new Threadpoolexecutor (0, Integer.max_value,                                      60L, Timeunit.seconds,                                      new synchronousqueue<runnable> ());    }
The minimum number of threads is 0, the maximum size is the integer maximum, which is equal to infinity, the blocking time is one minute, and if a thread is idle for more than 1 minutes, it is recycled.

Manage Queue Tasks

Choosing the right queue based on the size of the thread pool is good for leveraging resources and preventing exhaustion of resources.

There are 3 basic ways to queue up:

    • Unbounded queue
    • bounded queues
    • Synchronous handover

Newfixedthreadpool and Newsinglethreadpool will use a unbounded linkedblockingqueue by default. This queue increases indefinitely when all threads are busy.

A more secure resource management strategy is the use of bounded queues: such as Arrayblockingqueue, bounded linkedblockingqueue,priorityblockingqueue.

queue<string> que1 = new arrayblockingqueue<string> (200); queue<string> que2 = new linkedblockingdeque<string> (200); queue<string> que3 = new priorityblockingqueue<string> (200);

For very large or unbounded thread pools, you can avoid task queuing by using Synchronousqueue. and direct the transfer of tasks from producers to workers. It is not a real queue, but a mechanism for the handover of online threads. To put an element into Synchronousqueue, a thread must wait for the element to be accepted, and if no thread is waiting and the current size of the thread pool is the maximum value, then Threadpoolexecutor will create a new thread, otherwise, depending on the saturation policy, This task will be rejected.

Test code:

Import Java.util.concurrent.executorservice;import Java.util.concurrent.synchronousqueue;import Java.util.concurrent.threadpoolexecutor;import Java.util.concurrent.timeunit;public class ThreadTest { Executorservice exec = new Threadpoolexecutor (0, 2, 60L, Timeunit.seconds,new synchronousqueue<runnable> ()); private void Putrunnable () {for (int i = 0; i < 4; i++) {Exec.submit (new Runnable () {@Overridepublic void Run () {//TOD O auto-generated Method Stubwhile (True) {System.out.println (Thread.CurrentThread (). GetName ()); try {Thread.Sleep (500 );} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}});}} public static void Main (string[] args) {new ThreadTest (). putrunnable ();}}

The output results are as follows:

Pool-1-thread-1
Pool-1-thread-2
Exception in thread "main" Java.util.concurrent.RejectedExecutionException:Task [e-mail protected] rejected from [email p rotected][running, pool size = 2, active threads = 2, queued tasks = 0, completed tasks = 0]
At Java.util.concurrent.threadpoolexecutor$abortpolicy.rejectedexecution (Unknown Source)
At Java.util.concurrent.ThreadPoolExecutor.reject (Unknown Source)
At Java.util.concurrent.ThreadPoolExecutor.execute (Unknown Source)
At Java.util.concurrent.AbstractExecutorService.submit (Unknown Source)
At Threaddeadlock.putrunnable (threaddeadlock.java:12)
At Threaddeadlock.main (threaddeadlock.java:33)
Pool-1-thread-1
Pool-1-thread-2


A good default choice for the Executor,newcachedthreadpool factory approach is to provide better queueing performance than a fixed-size thread pool. This difference is due to the use of synchronousqueue instead of Linkedblockingqueu, a new non-blocking algorithm in JAVA6 to replace the JAVA5 algorithm, which uses them to increase throughput by 3 times times. When you need to limit the number of current tasks to meet resource management requirements, you can select a fixed-size thread pool. such as server applications that accept requests from network clients.

It is reasonable to set boundaries for the thread pool or work queue only when tasks are independent, and unbounded newcachethreadpool should be used if there are dependencies between tasks. Otherwise, a deadlock is likely to occur, that is, the task being performed waits for the execution result of the task not yet started.

Saturation Strategy

We see the last parameter in the Threadpoolexecutor constructor. Rejectedexecutionhandler handler. This is the saturation strategy.

The JDK provides several different implementations:

    • Discardoldestpolicy
    • AbortPolicy
    • Callerrunspolicy
    • Discardpolicy

AbortPolicy is the default saturation policy, which is to abort the task, and the policy will throw rejectedexecutionexception. The caller can catch the exception and then write code to handle the exception.

When a newly submitted task cannot be saved to the queue for execution, Discardpolicy discards the task slightly, Discardoldestpolicy discards the oldest (the next task to be performed), and then attempts to resubmit the new task. If the work queue is that priority queue, pairing with the discardoldestpolicy saturation policy causes the task with the highest priority to be discarded, so do not combine them.

Callerrunspolicy is a "caller run" policy that implements a throttling mechanism. It does not abandon the task, nor throws an exception. Instead, the task is rolled back to the caller. Instead of executing the task in the thread pool, it executes the task in a executor called

For example, we add the chestnut code above plus the saturation policy that the caller runs.

Import Java.util.concurrent.executorservice;import Java.util.concurrent.synchronousqueue;import Java.util.concurrent.threadpoolexecutor;import Java.util.concurrent.threadpoolexecutor.callerrunspolicy;import Java.util.concurrent.timeunit;public class Threaddeadlock {executorservice exec = new Threadpoolexecutor (0, 2, 60L, Timeunit.seconds,new synchronousqueue<runnable> (), New Callerrunspolicy ());p rivate void Putrunnable () {for (int i = 0; I < 4; i++) {exec.submit (new Runnable () {@Overridepublic void Run () {//TODO auto-generated method Stubwhile (True) {SYSTEM.OUT.P Rintln (Thread.CurrentThread (). GetName ()); try {thread.sleep ();} catch (Interruptedexception e) {//TODO Auto-generated catch Blocke.printstacktrace ();}}});}} public static void Main (string[] args) {new Threaddeadlock (). putrunnable ();}}

The resulting output will change to

Pool-1-thread-1
Main
Pool-1-thread-2
Pool-1-thread-1
Pool-1-thread-2
Main
Pool-1-thread-1
Pool-1-thread-2
Main
Pool-1-thread-2
Main
Pool-1-thread-1

The purpose of this is to have the task run in the commit task. This is because the time it takes to run itself will slow down the rate at which the task commits and buy time for the worker. Application in socket programming, the main thread stop accept, the arrival of the request will be saved in the TCP layer, when the TCP queue fills up, will also start to discard the request, which will cause the blocking has been passed to the client, to achieve a high load situation of a flat performance degradation.


When the work queue is filled, there is no pre-defined saturation policy to block execute (except for the abort and the caller to execute), but this does not prevent the task from being committed. This problem can be solved by semaphore.

Import Java.util.concurrent.executor;import Java.util.concurrent.executors;import Java.util.concurrent.rejectedexecutionexception;import Java.util.concurrent.semaphore;public class BounedExecutor {Private final Executor exec;private final Semaphore semaphore;public bounedexecutor (Executor exec, int bound) {super (); t His.exec = Exec;this.semaphore = new semaphore (bound);} public void Submittask (Final Runnable command) throws Interruptedexception {semaphore.acquire (); try {Exec.execute (new Runnable () {@Overridepublic void Run () {//TODO auto-generated method stubtry {System.out.println ("command.submit;"); Command.run ();} finally {semaphore.release ();}});} catch (Rejectedexecutionexception e) {semaphore.release ();}} public static void Main (string[] args) {Bounedexecutor is = new Bounedexecutor (Executors.newfixedthreadpool (3), 3); for ( int i = 0; I < 6; i++) {submittask (BE);}} private static void Submittask (Bounedexecutor be) {//TODO auto-generated method stubtry {be.submittask (new Runnable () {@Overridepublic void Run () {//TODO auto-generated method Stubwhile (True) {System.out.println (Thread.CurrentThread (). GetName ()); try {thread.sleep ($);} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}});} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}

The upper bound of the semaphore should be set to the size of the thread pool plus the number of lines that can be queued. This is because the semaphore requires the number of tasks under execution and waiting to be performed.


The results are as follows:

Command.submit;
Command.submit;
Pool-1-thread-1
Pool-1-thread-2
Command.submit;
Pool-1-thread-3
Pool-1-thread-1
Pool-1-thread-2
Pool-1-thread-3
Pool-1-thread-2

..

As you can see, the number of thread pool sizes has been submitted and no more tasks have been submitted.



The use of thread pool for Java concurrent Programming (ii)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.