java thread pool: use of Threadpoolexecutor
The concept of the Java thread pool is deeply understood by threadpoolexecutor The example of building bio pseudo asynchronous I/O communication.
-Thread vs Exector
First, to clear the ins and outs of Threadpoolexecutor ...
The method for creating threads in Java is as follows:
New Thread (New Runnable () {
@Override public
void Run () {
//TODO auto-generated method stub
}
}). STARRT ();
But there are the following drawbacks:
1. A task corresponds to a thread, when more concurrent tasks, the continuous creation and destruction of the thread on the system can have a greater impact;
2.thread class is not easy to manage the thread, no time execution, thread termination and other functions.
In order to adapt to the situation of multiple concurrency, reduce the overhead of system resources and reduce the congestion caused by competitive resources, a number of reusable threads can be created automatically or manually. When a configured thread is used, there is no control thread, other tasks in the task queue are waiting, and when one thread finishes the current task, it continues to pull the task out of the task queue, and the thread is idle if there are no tasks in the queue. The concept of thread pool arises. four class static thread pool
Exector as the top-level interface of the thread pool, the Java Exector interface provides four static factories that correspond to the four types of thread pools and inherit the Exectorservice interface.
1.executors.newcachedthreadpool () creates a cache pool of buffer pools with a size of integer.max_value, and if the thread pool length exceeds the processing needs, the free thread can be recycled flexibly, no recyclable thread, the new thread will be created.
2.executors.newfixedthreadpool (int) creates a fixed-line pool that controls the maximum number of concurrent threads, and the threads that are exceeded wait in the queue.
3, Executors.newscheduledthreadpool create a fixed-line pool, support the timing and periodic task execution.
4. Executors.newsinglethreadexecutor () creates a single-threaded (1) thread pool with a unique worker thread to perform the task, ensuring that all tasks are performed in the specified order (FIFO, LIFO, priority).
Among them, the Newcachedthreadpool (), Newfixedthreadpool (), Newsinglethreadexecutor () three static methods all return the Threadpoolexecutor instance, Newscheduledthreadpool () returns the Scheduledexecutorservice instance.
public static Executorservice newfixedthreadpool (int nthreads) {return
new Threadpoolexecutor (Nthreads, Nthreads,
0L, Timeunit.milliseconds,
new linkedblockingqueue<runnable> ());
public static Executorservice Newsinglethreadexecutor () {return
new Finalizabledelegatedexecutorservice
( New Threadpoolexecutor (1, 1,
0L, Timeunit.milliseconds,
new Linkedblockingqueue<runnable> ()));
public static Executorservice Newcachedthreadpool () {return
new Threadpoolexecutor (0, Integer.max_value,
60L , Timeunit.seconds,
new synchronousqueue<runnable> ());
public static Scheduledexecutorservice newscheduledthreadpool (int corepoolsize) {return
new Scheduledthreadpoolexecutor (corepoolsize);
}
In summary, the Exector genealogy chart is as follows:
(This picture borrows other people's blogs, in this thank moderator) Executor
The executor interface defines the Execute method that is used to perform a task, runnable is used to represent a task, and the interface provides a producer-consumer decoupling mechanism, submitting tasks equivalent to the producer, performing tasks rather than consumers;
Public interface Executor {
/**
* Executes the given command at some. The command
* May execute in a new thread, in a pooled thread, or
in the calling * thread, at the discretion of th e {@code Executor} implementation.
*
@param command the runnable task
* @throws Rejectedexecutionexception If this task cannot is
* accepted fo R execution
* @throws nullpointerexception if command is null
/void Execute (Runnable command);
}
Executorservice
The Executorservice interface inherits from the executor interface and is an extension of the executor excuse, providing a way to terminate a task and track one or more asynchronous tasks. Provides shutdown and Shutdownnow two ways to turn off Exectorservice and reject new tasks.
The shutdown () method allows the execution of previously submitted tasks before termination;
Shutdownnow prevents waiting for a task and stops the task from being performed at this stage.
The Exector.execycute (Runnable) method is used to create and return future tasks that are sadly canceled or waiting to be completed, Invokeany or InvokeAll invoke tasks in the task queue, and wait for at least one meeting to be completed on all tasks.
Application Examples:
Class NetworkService implements Runnable {
private final serversocket serversocket;
Private final Executorservice pool;
public NetworkService (int port, int poolsize)
throws IOException {
serversocket = new ServerSocket (port);
Pool = Executors.newfixedthreadpool (poolsize);
}
public void Run () {//Run the service
try {for
(;;) {
Pool.execute (new Handler (Serversocket.accept ()));
}
catch (IOException ex) {
pool.shutdown ();
}}} Class Handler implements Runnable {
private final socket socket;
Handler (socket socket) {this.socket = socket;}
public void Run () {
//Read and service request on Socket}}}
Threadpoolexecutor Constructor Description
Public threadpoolexecutor (int corepoolsize, int maximumpoolsize, Long KeepAliveTime, timeunit unit, Blockingqueue<ru Nnable> workqueue) {This (corepoolsize, maximumpoolsize, KeepAliveTime, Unit, Workqueue, executors
. Defaultthreadfactory (), DefaultHandler);
Public threadpoolexecutor (int corepoolsize, int maximumpoolsize, Long KeepAliveTime, timeunit unit, blockingqueue< Runnable> Workqueue, Threadfactory threadfactory) {This (corepoolsize, Maximumpoo
Lsize, KeepAliveTime, Unit, Workqueue, Threadfactory, DefaultHandler);
Public threadpoolexecutor (int corepoolsize, int maximumpoolsize,Long KeepAliveTime, timeunit unit, BLOCKINGQUEUE<RUNNABLE&G T Workqueue, Rejectedexecutionhandler handler) {This (Corepoolsize, Maximumpoolsize, K
Eepalivetime, Unit, Workqueue, Executors.defaultthreadfactory (), handler);
Public threadpoolexecutor (int corepoolsize, int maximumpoolsize, Long KeepAliveTime, timeunit unit, Blockingqueue<r Unnable> Workqueue, Threadfactory threadfactory, Rejectedex
Ecutionhandler handler) {if (Corepoolsize < 0 | | |
Maximumpoolsize <= 0 | |
Maximumpoolsize < Corepoolsize | |
KeepAliveTime < 0) throw new IllegalArgumentException (); if (Workqueue = null | | threadfactory = NULL | | handLer = = null) throw new NullPointerException ();
This.corepoolsize = corepoolsize;
This.maximumpoolsize = maximumpoolsize;
This.workqueue = Workqueue;
This.keepalivetime = Unit.tonanos (KeepAliveTime);
This.threadfactory = threadfactory;
This.handler = handler; }
. corepoolsize
The number of core threads, by default, the core thread survives, even if it is idle and is not subject to the KeepAliveTime limit. Unless you set Allowcorethreadtimeout to True.
. maximumpoolsize
The maximum number of threads that the thread pool can hold. Threads exceeding this number will be blocked. This value is not valid when the task team is listed as Linkedblockingdeque with no set size.
. KeepAliveTime
Idle timeout for non-core threads, more than this time will be reclaimed.
. Unit
Specifies the unit of the KeepAliveTime, such as Timeunit.seconds. The corepoolsize takes effect when the Allowcorethreadtimeout is set to true. Workqueue
The queue of tasks in the thread pool.
There are three kinds of queues commonly used,synchronousqueue,linkedblockingdeque,arrayblockingqueue. thread pool Execution rules for threads
all of the following assume that the task queue does not have a size limit:
1. If the threadsize<=corepoolsize, then directly start a core thread to perform the task, will not be placed in the queue.
2. If threadsize>corepoolsize, but <=maximumpoolsize, and task queues are linkedblockingdeque, tasks that exceed the number of core threads are queued in the task queue.
3. If threadsize>corepoolsize, but <=maximumpoolsize, and the task queue is synchronousqueue, the line Cheng creates a new thread to perform the task, and the tasks are not placed in the task queue. These threads belong to a non-core thread, and when the task completes, idle time reaches the time-out period and is cleared.
4. If threadsize>corepoolsize, and >maximumpoolsize, when the task queue is Linkedblockingdeque, the tasks that exceed the core thread are queued in the task queue. That is, when the task queue is linkedblockingdeque and there is no size limit, the maximum number of threads in the thread pool setting is invalid, and his number of threads does not exceed the core thread count.
5. If threadsize>corepoolsize, and >maximumpoolsize, when the task queue is synchronousqueue, it throws an exception because the thread pool refuses to add the task.
when the task queue size is limited
When Linkedblockingdeque is full, new tasks are created directly to execute, and exceptions are thrown when the number of threads created exceeds the maximum number of threads.
Synchronousqueue is not limited in quantity. Because he does not maintain these tasks, but directly to the thread pool to execute. Exceptions are thrown directly when the number of tasks exceeds the maximum number of threads.