Thread pool Threadpoolexecutor Use

Source: Internet
Author: User
1. Notes

Recently, the author encountered such a problem in the development. When the author deletes a record through the Web interface, the system always reports "system error", and the thought of the deleted data is not deleted. Looking at the Tomcat log, I found the following error reported:

Java.util.concurrent.RejectedExecutionException 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)

If the reader is familiar with the thread, it will know at a glance that the error is related to the thread, which means that the deletion code was rejected by the thread when I performed a delete record. That's weird, why is it good that the thread will refuse to execute my code? Through the tracking code, the author found that our system for the processing of threads are sad thread pool calls, that is, the current processing may be exceeded the size of the thread pool, so it was refused to execute. Well, I know the problem, the size of the thread pool has been modified, if the problem is solved. But in order to take a step to understand the thread pool, today I summed up the thread pool usage. 2. Introduction of Threadpoolexecutor

Through the above error information, we also know that the thread pool class is java.util.concurrent.ThreadPoolExecutor. Through the source code, we can see the function of this method as follows:

Public threadpoolexecutor (int corepoolsize,
                              int maximumpoolsize,
                              long KeepAliveTime,
                              timeunit Unit,
                              blockingqueue<runnable> Workqueue,
                              Rejectedexecutionhandler handler) {This
        (corepoolsize, maximumpoolsize, KeepAliveTime, Unit, Workqueue,
             Executors.defaultthreadfactory (), handler);
We can see that there are six parameters in total, so how do these logarithms work? The author through the following table to explain:

The role of these parameters, online also gives the following points:

1 if the thread running in the thread pool is less than corepoolsize, a new thread is created to handle the added task even if the thread in the thread pool is idle.

2 If the threads running in the thread pool are greater than or equal to corepoolsize, but the buffer queue Workqueue is not full, then the task is put into the buffer queue.

3 If the number of threads in the thread pool is greater than corepoolsize, the buffer queue Workqueue full (that is, the request cannot be queued), and the number of threads in the pool is less than maximumpoolsize, a new thread is built to handle the added task.

4 If the number of threads in the thread pool is greater than corepoolsize, the buffer queue is workqueue full, and the number in the thread pool equals maximumpoolsize, the task is handled through the policy specified by handler.

5 when the number of threads in the thread pool is greater than corepoolsize, the thread is terminated if a thread is idle longer than KeepAliveTime. This allows the thread pool to dynamically adjust the number of threads in the pool.

That is, the priority of the processing task is: corepoolsize, Task queue workqueue, maximum thread maximumpoolsize, if all three are full, use handler to process the rejected task.

These two errors are often thrown when using the thread pool: illegalargumentexception, NullPointerException. So under what circumstances throw illegalargumentexception, and under what circumstances throw NullPointerException error? The following table gives directions:
3. Examples illustrate

1)          First, create a common thread pool. Here is the new one Threadpoolexexutor class, for the processing of thread rejection tasks, we give two scenarios, namely, the use of bounded queue policies and the use of unbounded queue policies. Unbounded queues, we use linkedblockingqueue; Bounded queues are arrayblockingqueue. It is important to note that the use of unbounded Queuw may deplete system resources, and using a bounded queue may not be good for performance, requiring the number of calls and queue sizes.

Import Java.util.concurrent.ArrayBlockingQueue;
Import Java.util.concurrent.BlockingQueue;
Import Java.util.concurrent.LinkedBlockingQueue;
Import Java.util.concurrent.RejectedExecutionHandler;
Import Java.util.concurrent.ThreadPoolExecutor;

Import Java.util.concurrent.TimeUnit; /** * Create thread pool * * @author Owenwilliam * @Date 2017-4-17 */public class ThreadPool {public static final int Arra Y_queue = 0; Arrayblockingqueue bounded queue policy public static final int linked_queue = 1;
	Linkedblockingqueue uses the unbounded queue strategy private Threadpoolexecutor executor;

	Private blockingqueue<runnable> Workqueue;            /** * @param workquenesize * Queue Length * @param coresize * Number of main threads * @param maxSize * Maximum number of threads * @param queuetype * Queue type/public ThreadPool (final int workquenesize, final int coresize, FI
	nal int maxSize, int queuetype) {This (workquenesize, Coresize, maxSize, queuetype, NULL);          }/** * * @param workquenesize *  Queue Length * @param coresize * Main thread number * @param maxSize * Maximum number of threads * @param queuetype * Queue type * @param policy * processing policy/public ThreadPool (final int workquenesize, final int coresize, final
		int maxSize, int queuetype, Rejectedexecutionhandler policy) {workqueue = Createqueue (Queuetype, workquenesize); Executor = new Threadpoolexecutor (coresize, MaxSize, Timeunit.seconds, workqueue, policy!= null? Policy:
	New Threadpoolexecutor.abortpolicy ()); } public void execute (Runnable Runnable) {if (Workqueue.size () > 4) {System.out.println ("Currently waiting thread Size: '" +ru
		Nnable.getclass (). Getsimplename () + "':" +workqueue.size ());
	} executor.execute (runnable);  /** * Create queues, select different and queue policies * Arrayblockingqueue bounded queue policy * linkedblockingqueue use unbounded queue policy * @param queuetype * @param Queuesize * @return * * Private blockingqueue<runnable> createqueue (int queuetype, int queuesize) {return q UEuetype = = Linked_queue?
	New Linkedblockingqueue<runnable> (queuesize): New arrayblockingqueue<runnable> (queueSize);
	Public blockingqueue<runnable> Getqueue () {return executor.getqueue ();

2 Create a thread.

/** *
 Single thread
 * @author owenwilliam
 * @Date 2017-4-17 * */Public
class Threadrunnable implements Runnable

	String name;

	Public threadrunnable (String name)
	{ = name;

	@Override public
	Void Run ()
		//Process a task, the processing here is too simple, just a print statement
		System.out.println ("Start ..." + name);
			//easy to observe, wait a period of time
		} catch (Exception e)
			e.printstacktrace () ;



3 Create a class call thread pool and threads.

 * Use thread pool
 * * 
 @author owenwilliam
 * @Date 2017-4-17 * */Public
class Usthreadpool

	private ThreadPool tp;
	private static Usthreadpool pool = new Usthreadpool ();

	Private Usthreadpool ()
		int workquenesize =;
		int coresize = 4;
		int maxSize = ten;

		Create thread pool
		TP = new ThreadPool (workquenesize, Coresize, MaxSize,

	public static Usthreadpool Getpool ()

	public void execute (Runnable Runnable)
		tp.execute (Runnable);

	public void execute (String name)
		Execute (new threadrunnable (name));

4 finally write a test class.

/** *
 Test thread * * 
 @author owenwilliam
 * @Date 2017-4-17 * */Public
class testthread< c40/>{public

	static void Main (string[] args)

		(int i = 0; i < i++)
		{ Tpool (). Execute ("num:" + i);}}}

4. Implementation results


Source Address:

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: 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.