Overview
Excutor this interface with a few, but threadpoolexcutor this is used more, Threadpoolexcutor is excutor an implementation. Excutor system Difficulties No, most of the key points and design ideas are described in the Javadoc in particular, but it is necessary to do a comb, in order to better use in the subsequent development scenarios, the flexible API provided by the JDK.
The Excutor interface is primarily used for decoupling task performers and task initiators, and Jdk8 's Javadoc is written in very detailed detail. Therefore, Excutor this series of classes are directed at this goal to achieve, of course, many implementation classes are more in the specific scene of the implementation of the field, so that developers save time and worry, such as threadpoolexcutor to the thread pool management, The Scheduledthreadpoolexecutor provides thread pool functionality while also supporting timing and fixed-frequency tasks.
An object, that executes submitted Runnable tasks. This interface provides a by decoupling task submission from the mechanics of what each task would be run, including Det Ails of thread use, scheduling, etc.
Class diagram
Extended Interface Executorservice
Executorservice Executor is enhanced to track/manage/stop tasks. Description of Javadoc:
An, Executor provides methods to manage termination and methods, can produce a for Future tracking progress of one or More asynchronous tasks.
an executorservice can is shut down, which'll cause it to reject new tasks. Different methods is provided for shutting down an executorservice . the shutdown () method'll allow previously submitted tasks to execute before terminating, while T he shutdownnow () method prevents waiting tasks from starting and attempts to stop currently execut ing tasks. Upon termination, an executor have no tasks actively executing, no tasks awaiting execution, and no new tasks can be submit Ted. an unused executorservice should is shut down to allow reclamation of the its resources.
Method submit extends base method by Executor.execute(Runnable) creating and returning a so Future can be used to cancel execution and/or wait For completion. Methods invokeAny invokeAll and perform the most commonly useful forms of bulk execution, executing a collection of tasks and then Waiting for at least one, or all, to complete. (Class ExecutorCompletionService can be used to write customized variants of these methods.)
Executorservice is based on typical usage scenarios and is extended to Abstractexecutorservice and Scheduledexecutorservice as the interface for real-time task processing and the latter as the processing interface for timed/fixed-frequency tasks.
Abstractexecutorservice
Abstractexecutorservice is positioned as the processing of a real-time task, so submit returns a Futuretask object that the caller can use to track the task.
Provides default implementations of ExecutorService execution methods. This class implements submit the, invokeAny and invokeAll methods using a RunnableFuture returned newTaskFor by, which defaults to the FutureTask clas s provided in the this package. For example, the implementation of submit(Runnable) creates a associated that is RunnableFuture executed and returned. Subclasses may override the newTaskFor methods to return RunnableFuture implementations other than FutureTask .
Scheduledexecutorservice
The
Scheduledexecutorservice extends the Executorservice, adds timing and fixed-frequency control, and actually Scheduledexecutorservice also supports the real-time execution API (Excute ()), and , which by default is handled in the real-time task when the delay parameter value is 0 or negative. Scheduledexecutorservice's Submit method returns the Scheduledfuturetask. Description of the Javadoc:
An ExecutorService the can schedule commands to run after a given delay, or to execute periodically.
The schedule methods create tasks with various delays and return a task object The can is used to cancel or check execution. The scheduleAtFixedRate and scheduleWithFixedDelay methods Create and execute tasks that run periodically until cancelled.
Commands submitted using the Executor.execute(Runnable) and ExecutorService submit methods is scheduled with a requested delay of zero. Zero and negative delays (but not periods) is also allowed schedule in methods, and is treated as requests for immediate EX Ecution.
A useful implementationThreadPoolExecutor
Threadpoolexecutor usually used more often, the use of the Executors tool class three methods are sufficient, if you need to customize the thread pool, you need to focus on the queue and the thread pool size of several parameters of the use of the combined. Javadoc write the more detailed, excerpt down, the marked part is the focus:
An so ExecutorService executes each submitted task using one of possibly several pooled threads, normally configured using Executors F Actory methods.
Thread Pools address different problems:they usually provide improved performance when executing large numbers of asy nchronous tasks, due to reduced per-task invocation overhead, and they provide a means of bounding and managing the Resour CES, including threads, consumed when executing a collection of tasks. Each ThreadPoolExecutor also maintains some basic statistics, such as the number of completed tasks.
To is useful across a wide range of contexts, this class provides many adjustable parameters and extensibility hooks. However, programmers is urged to use the more convenient Executors factory methods Executors.newCachedThreadPool() (unbounded thread pool, with Automat IC thread Reclamation), Executors.newFixedThreadPool(int) (fixed size thread pool) Executors.newSingleThreadExecutor() and (single background thread), that preconfigure settings fo R the most common usage scenarios. Otherwise, use the following if manually configuring and tuning this class:
-
-
Core and Maximum pool sizes
-
A ThreadPoolExecutorWould automatically adjust the pool size (see getPoolSize()) According to the bounds set by Corepoolsize (see getCorePoolSize()) and Maximumpoolsize (see getMaximumPoolSize()). When a new task was submitted in method execute(Runnable) , and fewer than corepoolsize threads was running, a new thre Ad is created to handle the request, even if and worker threads is idle. If there is more than corepoolsize but less than maximumpoolsize threads running, a new thread would be created only if th E queue is full. By setting Corepoolsize and maximumpoolsize the same, you create a fixed-size thread pool. By setting Maximumpoolsize to an essentially unbounded value such as Integer.MAX_VALUE, you allow the pool to accommodate a arbitrary number of concurrent tasks. Most typically, core and maximum pool sizes is set only upon construction, but they could also be changed dynamically using setCorePoolSize(int)and setMaximumPoolSize(int).
-
-
On-demand Construction
-
-
by default, even core threads is initially created and started only if new tasks arrive, but this can is Overrid Den dynamically using Method prestartCoreThread() or prestartAllCoreThreads() . You probably want to prestart threads if you construct the pool with a non-empty queue.
-
-
Creating New threads uses custom factory to group threads and set different priorities.
-
New threads is created using a ThreadFactory. If not otherwise specified, a Executors.defaultThreadFactory()is used, which creates threads to all being in the same ThreadGroupAnd with the same NORM_PRIORITYPriority and Non-daemon status. By supplying a different threadfactory, you can alter the thread's name, thread group, priority, daemon status, etc. If A ThreadFactoryFails to create a thread when asked by returning null from newThread, the executor would continue, but might is not being able to execute any tasks. Threads should possess the "Modifythread" RuntimePermission. If worker threads or other threads using the pool does not possess this permission, service could be degraded:configuration C Hanges effect in a timely manner, and a shutdown pool could remain in a state in which termination are possible But not completed.
-
-
Keep-alive Times
-
-
If the pool currently have more than corepoolsize threads, excess threads would be terminated If they h Ave been idle For more than the KeepAliveTime (see getkeepalivetime (timeunit) ). This provides a means of reducing resource consumption when the pool was not being actively used. If the pool becomes more active later, new threads'll be constructed. This parameter can also is changed dynamically using method setkeepalivetime (Long, timeunit) . Using a value of long.max_value timeunit.nanoseconds effectively disables Idle threads from ever terminating prior to shut down. By default, the Keep-alive policy applies only if there is more than corepoolsize threads. But method allowcorethreadtimeout (Boolean) can is used to apply this time-out policy to core THR EADS as well, so long as the KeepAliveTime value is Non-zero.
-
-
Queuing focuses on: direct delivery, unbounded queuing, bounded queue-specific, and typical usage scenarios.
-
Any BlockingQueueMay is used to transfer and hold submitted tasks. The use of this queue interacts with pool sizing:
- If fewer than corepoolsize threads is running, the Executor always prefers adding a new thread rather than queuing.
- If corepoolsize or more threads is running, the Executor always prefers queuing a request rather than adding a new thread .
- If a request cannot be queued, a new thread was created unless this would exceed maximumpoolsize, in which case, the task W Ill be rejected.
There is three general strategies for queuing:
- Direct handoffs. a good default choice for A Work queue is a ,
synchronousqueue that Hands off tasks to threads Without otherwise holding them. Here, an attempt to queue a task would fail if no threads is immediately available to run it, so a new thread would be cons Tructed. this policy avoids lockups when handling sets of requests that might has Internal dependencies. Direct handoffs generally require unbounded maximumpoolsizes to avoid rejection of new submitted tasks. The turn admits the possibility of unbounded thread growth when commands continue to arrive on average faster than the Y can be processed.
- unbounded queues. using an unbounded queue (for example a
linkedblockingqueue without a predefined capacity) Would cause new tasks to wait for the queue when all corepoolsize threads is busy. Thus, no more than corepoolsize threads would ever be created. (and the value of the Maximumpoolsize therefore doesn ' t has any effect.) this May was appropriate when each task was completely independent of other s, so tasks cannot affect each others execution; For example, in a Web page server. while this style of queuing can is useful in smoothing out transient bursts of requests, it admits the Possibilit Y of unbounded Work queue growth if commands continue to arrive on average faster than they can be processed.
- bounded queues. A bounded queue (for example, an
ArrayBlockingQueue ) helps prevent resource exhaustion when used with finite maximumpoolsizes, but can Be more difficult to tune and control. Queue sizes and Maximum pool sizes May is traded off for each other:using large queues and small pools minimizes CPU USAG E, OS resources, and context-switching overhead, but can leads to artificially low throughput. If tasks frequently block (for example if they is I/O bound), a system may is able to schedule time for more threads than You otherwise allow. Use of small queues generally requires larger pool sizes, which keeps CPUs busier but may encounter unacceptable Schedulin G overhead, which also decreases throughput.
-
-
Rejected tasks
-
New tasks submitted in method execute(Runnable)would be rejectedWhen the Executor have been shut down, and also then the Executor uses finite bounds for both maximum threads and work Queu e capacity, and is saturated. In either case, the executeMethod invokes the RejectedExecutionHandler.rejectedExecution(Runnable, ThreadPoolExecutor)Method of its RejectedExecutionHandler. Four predefined handler policies is provided:
ThreadPoolExecutor.AbortPolicyin the default, the handler throws a runtime RejectedExecutionException upon rejection.
ThreadPoolExecutor.CallerRunsPolicyin, the thread that invokes execute itself runs the task. This provides a simple feedback control mechanism, that would slow down the rate that new tasks is submitted.
ThreadPoolExecutor.DiscardPolicyin, a task, the cannot be executed is simply dropped.
- In
ThreadPoolExecutor.DiscardOldestPolicy , if the executor isn't shut down, the task at the head of the work queue was dropped, and then execution is Retri Ed (which can fail again, causing this to is repeated.)
It is possible to define and use other kinds of RejectedExecutionHandlerClasses. Doing so requires some care especially when policies is designed to work only under particular capacity or queuing polici Es.
-
-
Hook methods functions for extending the thread pool
-
This
-
class provides protected overridable and methods that is beforeExecute(Thread, Runnable) afterExecute(Runnable, Throwable) called before and after Executi On the each task. These can used to manipulate the execution environment; For example, Reinitializing threadlocals, gathering statistics, or adding log entries. Additionally, method terminated() can be overridden to perform any special processing that needs to being done once the Executor has fully terminated.
If Hook or callback methods throw exceptions, internal worker threads may in turn fail and abruptly terminate.
Forkjoinpool
Forkjoinpool follows the idea of ' divide and conquer ', splits the task first, and, if necessary, finally merges the result of the task and returns it. It can only perform tasks of type Forkjointask, where the Recursivetask task has a return result after execution, and Recursiveaction does not return a result, which is appropriate for the event-driven class's task.
Excutors
Excutors is a tool class that provides APIs for creating typical Threadpoolexcutor and Scheduledthreadpoolexecutor instances, often without creating a thread pool by themselves, using the API of this tool class.
Summarize
The Excutor system in the Java Cocurrent package provides real-time and timed (with fixed frequency) Excutor, support for a single thread, and a thread pool; their role is to decouple task performers from task publishers.
Real-time task processing can be a special case for timed tasks, and Scheduledthreadpoolexecutor also provides APIs to support real-time tasks.
Thread pool creation is typically done using excutors, a typical thread pool: a single, fixed-size thread pool, an adjustable-size thread pool, and a custom thread pool that requires a good mix of queue size and thread pool size.
Use the Submit API to bring the task to the thread pool, according to the actual scenario, through the corresponding future interface implementation of the class API to monitor the task execution, if necessary, you can stop the execution of the task.
Use process: Create a thread pool, create tasks, submit tasks, track and process task results.
Java Concurrency Program Foundation--excutor