Fork/Join(3):ForkJoinPool之API翻译

来源:互联网 发布:网络销售彩票诈骗流程 编辑:程序博客网 时间:2024/05/17 14:25

Fork/Join(3):ForkJoinPool之API翻译


ForkJoinPool是Fork/Join框架的两大核心类之一,这一节先翻译API,具体使用方法和实现原理留待后续章节再谈。

虽然fork/join框架从JDK1.7开始就已经存在,但介绍Fork/Join框架的文章比较少,且大多数都是简单应用。要学习一个框架,从API文档开始或许是一个不错的方式。

特别说明:英文版本来源于JDK1.8_40 API。


第一次尝试翻译英文技术文档,翻译可能并不准确,所以保留了英文。如有错误还望指正!谢谢!

以下为翻译内容:

 

An ExecutorService for runningForkJoinTasks. AForkJoinPool provides the entry point for submissions from non-ForkJoinTask clients, as well as management and monitoring operations.

A ForkJoinPool differs from other kinds ofExecutorService mainly by virtue of employingwork-stealing: all threads in the pool attempt to find and execute tasks submitted to the pool and/or created by other active tasks (eventually blocking waiting for work if none exist). This enables efficient processing when most tasks spawn other subtasks (as do mostForkJoinTasks), as well as when many small tasks are submitted to the pool from external clients. Especially when settingasyncMode to true in constructors,ForkJoinPools may also be appropriate for use with event-style tasks that are never joined.

A static commonPool() is available and appropriate for most applications. The common pool is used by any ForkJoinTask that is not explicitly submitted to a specified pool. Using the common pool normally reduces resource usage (its threads are slowly reclaimed during periods of non-use, and reinstated upon subsequent use).

一个运行ForkJoinTask的ExecutorService,ForkJoinPool 提供了非ForkJoinTask客户端的提交入口及管理监控操作。

ForkJoinPool与其它类型的ExecutorService相比,其主要的不同在于采用工作窃取算法(work-stealing)所有池中线程会尝试找到并执行已被提交到池中的其他活动任务创建任务(阻塞直到没有任务存在)。这使得能够有效地处理以下情景:大多数由任务产生大量子任务的情况(譬如ForkJoinTasks)从外部客户端大量提交小任务到池中的情况特别强调,如在构造函数asyncMode(异步模式)设置为true,当其未被加入时,ForkJoinPools也可适当用于事件式任务。

静态方法commonPool()可适用于大多数应用程序。common pool用于任意没有明确提交到指定池的ForkJoinTask使用common pool通常可降低资源占用(周期内未被使用的线程会被缓慢回收,并回复可用状态)。

 

For applications that require separate or custom pools, aForkJoinPool may be constructed with a given target parallelism level; by default, equal to the number of available processors. The pool attempts to maintain enough active (or available) threads by dynamically adding, suspending, or resuming internal worker threads, even if some tasks are stalled waiting to join others. However, no such adjustments are guaranteed in the face of blocked I/O or other unmanaged synchronization. The nestedForkJoinPool.ManagedBlocker interface enables extension of the kinds of synchronization accommodated.

In addition to execution and lifecycle control methods, this class provides status check methods (for examplegetStealCount()) that are intended to aid in developing, tuning, and monitoring fork/join applications. Also, methodtoString() returns indications of pool state ina convenient form for informal monitoring.

As is the case with other ExecutorServices, there are three main task execution methods summarized in the following table. These are designed to be used primarily by clients not already engaged in fork/join computations in the current pool. The main forms of these methods accept instances ofForkJoinTask, but overloaded forms also allow mixed execution of plainRunnable- orCallable- based activities as well. However, tasks that are already executing in a pool should normally instead use the within-computation forms listed in the table unless using async event-style tasks that are not usually joined, in which case there is little difference among choice of methods.

如需自定义应用或者线程池,ForkJoinPool可以使用给定的并行度,默认值是可用的处理器数量。线程池通过动态添加、暂停或恢复内部工作线程来保持足够的活动(或可用)线程,即使某些任务在等待加入时处于停滞状态。通常,阻塞I/O或非托管同步并没有提供调节机制,嵌套接口类ForkJoinPool.ManagedBlocker是可扩展的同步容器。

除了执行任务和控制生命周期方法,提供状态检查方法(如getstealcount()),旨在帮助开发调试监测Fork/join应用,而tostring()方法则在适当的时点从非正式监控状态中返回线程池状态标识

与其他executorservice比较,有三个主要任务执行方法总结在下表中。这些设计主要用于运行还未在当前线程池中fork/join任务。这些方法主要接受forkjointask实例,但重载形式允许混合执行Runnable或Callable任务。通常,任务在池中运行时采用表中列出的执行方式,因此除非采用异步事件任务方式,否则不会执行join操作,在此情况下,这些方法之间只有少许区别

Summary of task execution methods

 

Call from non-fork/join clients

Call from within fork/join computations

Arrange async execution

execute(ForkJoinTask)

ForkJoinTask.fork()

Await and obtain result

invoke(ForkJoinTask)

ForkJoinTask.invoke()

Arrange exec and obtain Future

submit(ForkJoinTask)

ForkJoinTask.fork() (ForkJoinTasksare Futures)

 

common pool的默认构造方法采用默认参数,但有三个系统参数可选:

java.util.concurrent.ForkJoinPool.common.parallelism -并行级别(非负整数)

java.util.concurrent.ForkJoinPool.common.threadFactory -ForkJoin线程工厂 ForkJoinPool.ForkJoinWorkerThreadFactory 

java.util.concurrent.ForkJoinPool.common.exceptionHandler -未捕获异常持有器Thread.UncaughtExceptionHandler 

 

If a SecurityManager is present and no factory is specified, then the default pool uses a factory supplying threads that have noPermissions enabled. The system class loader is used to load these classes. Upon any error in establishing these settings, default parameters are used. It is possible to disable or limit the use of threads in the common pool by setting the parallelism property to zero, and/or using a factory that may returnnull. However doing so may cause unjoined tasks to never be executed.

如果存在SecurityManager,且未指定线程工厂,则默认池将没有权限启用工厂提供线程。系统类加载器用于加载这些类。在建立这些设置时发生任何错误,将使用默认参数。通过将并行属性设置为零,或使用可能返回null的工厂,可以禁用或限制common pool中线程使用,但这样做可能导致未加入的任务从不执行。

 

Implementation notes:

This implementation restricts the maximum number of running threads to 32767. Attempts to create pools with greater than the maximum number result inIllegalArgumentException.

This implementation rejects submitted tasks (that is, by throwingRejectedExecutionException) only when the pool is shut down or internal resources have been exhausted.

实现说明:

此实现限制运行线程的最大数量32767试图创建超过最大数量的线程时将抛出IllegalArgumentException。只有当线程池关闭或内部资源枯竭才会拒绝提交任务(抛出RejectedExecutionException)

Since: 1.7

 

嵌套类摘要

Nested Classes 

Modifier and Type

Class and Description

static interface 

ForkJoinPool.ForkJoinWorkerThreadFactory 

创建新的ForkJoinWorkerThreads的工厂

static interface 

ForkJoinPool.ManagedBlocker 

ForkJoinPools用于扩展并行级别管理的接口

Interface for extending managed parallelism for tasks running inForkJoinPools.

 

属性摘要

Fields

 

Modifier and Type

Field and Description

static ForkJoinPool.ForkJoinWorkerThreadFactory

defaultForkJoinWorkerThreadFactory 

创建一个新的ForkJoinWorkerThread。

 

构造方法摘要

Constructors 

Constructor and Description

ForkJoinPool() 

创建一个ForkJoinPool:使用Runtime.availableProcessors()获取的数值作为并行级别;使用默认的default thread factoryUncaughtExceptionHandler为空;非异步LIFO模式。

ForkJoinPool(int parallelism) 

创建一个ForkJoinPool:使用指定数值作为并行级别;使用默认的default thread factoryUncaughtExceptionHandler为空;非异步LIFO模式。

ForkJoinPool(int parallelism,ForkJoinPool.ForkJoinWorkerThreadFactory factory,Thread.UncaughtExceptionHandler handler, boolean asyncMode) 

使用指定参数创建一个ForkJoinPool。

 

方法摘要

All Methods  

Modifier and Type

Method and Description

boolean

awaitQuiescence(long timeout,TimeUnit unit) 

如果被此池中的ForkJoinTask调用,等价于此方法:

ForkJoinTask.helpQuiesce()

If called by a ForkJoinTask operating in this pool, equivalent in effect toForkJoinTask.helpQuiesce().

boolean

awaitTermination(long timeout,TimeUnit unit) 

阻塞直到所有任务执行完毕。当任意以下情况出现则停止阻塞,以先发生为准:收到关闭请求、超时、线程中断。

Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first.

static ForkJoinPool

commonPool()

返回common pool 实例。

Returns the common pool instance.

protected int

drainTasksTo(Collection<? superForkJoinTask<?>> c) 

移除任务调度队列中所有未有效提交和已分解的任务,并将它们添加到给定的集合,但不改变其执行状态。

Removes all available unexecuted submitted andforked tasks from scheduling queues and adds them to the given collection, without altering their execution status.

void

execute(ForkJoinTask<?> task) 

安排(异步)执行给定任务。

Arranges for (asynchronous) execution of the given task.

void

execute(Runnable task) 

在未来的某个时间执行给定任务。

Executes the given command at some time in the future.

int

getActiveThreadCount() 

返回当前正在窃取或执行任务的线程数的估计值。

Returns an estimate of the number of threads that are currently stealing or executing tasks.

boolean

getAsyncMode() 

当使用先进先出模式时返回true

Returns true if this pool uses local first-in-first-out scheduling mode for forked tasks that are never joined.

static int

getCommonPoolParallelism() 

返回common pool的目标并行级别

Returns the targeted parallelism level of the common pool.

ForkJoinPool.ForkJoinWorkerThreadFactory

getFactory() 

返回线程工厂用于构造新的线程。

Returns the factory used for constructing new workers.

int

getParallelism() 

返回这个线程池的目标并行度

Returns the targeted parallelism level of this pool.

int

getPoolSize() 

返回已启动但尚未终止的工作线程数。

Returns the number of worker threads that have started but not yet terminated.

int

getQueuedSubmissionCount() 

返回还未开始运行的任务数的估计值。

Returns an estimate of the number of tasks submitted to this pool that have not yet begun executing.

long

getQueuedTaskCount() 

返回工作线程的任务队列中总任务数的估计值(但不包括提交到池中但未开始执行的任务)。

Returns an estimate of the total number of tasks currently held in queues by worker threads (but not including tasks submitted to the pool that have not begun executing).

int

getRunningThreadCount() 

返回处于未阻塞状态等待加入任务或其它同步管理的工作线程数的估计值。

Returns an estimate of the number of worker threads that are not blocked waiting to join tasks or for other managed synchronization.

long

getStealCount() 

返回从其它线程任务队列中窃取的任务数估计值。

Returns an estimate of the total number of tasks stolen from one thread's work queue by another.

Thread.UncaughtExceptionHandler

getUncaughtExceptionHandler() 

返回内部工作线程在执行任务时遇到不可恢复的错误时的处理程序。

Returns the handler for internal worker threads that terminate due to unrecoverable errors encountered while executing tasks.

boolean

hasQueuedSubmissions() 

当存在已提交到当前线程池但尚未执行的任务时返回true。

Returns true if there are any tasks submitted to this pool that have not yet begun executing.

<T> T

invoke(ForkJoinTask<T> task) 

执行给定任务,完成后返回结果。

Performs the given task, returning its result upon completion.

<T> List<Future<T>>

invokeAll(Collection<? extendsCallable<T>> tasks) 

执行给定的任务列表,返回持有任务状态和任务完成时的结果的Future列表。

Executes the given tasks, returning a list of Futures holding their status and results when all complete.

boolean

isQuiescent()

当所有工作线程处于空闲时返回true。

Returns true if all worker threads are currently idle.

boolean

isShutdown() 

此线程池已被关闭时返回true。

Returns true if this pool has been shut down.

boolean

isTerminated() 

如果此池关闭后所有任务已停止,返回true

Returns true if all tasks have completed following shut down.

boolean

isTerminating() 

如果此线程池正在终止任务但尚未全部终止,返回true。

Returns true if the process of termination has commenced but not yet completed.

static void

managedBlock(ForkJoinPool.ManagedBlocker blocker) 

运行给定的可能阻塞任务。

Runs the given possibly blocking task.

protected <T> RunnableFuture<T>

newTaskFor(Callable<T> callable) 

返回给定callable任务的RunnableFuture。

Returns a RunnableFuture for the given callable task.

protected <T> RunnableFuture<T>

newTaskFor(Runnable runnable, T value) 

返回给定runnable任务和给定值的RunnableFuture

Returns a RunnableFuture for the given runnable and default value.

protected ForkJoinTask<?>

pollSubmission() 

如果存在下一个未运行的可用的已提交任务,将其返回并在任务队列中删除

Removes and returns the next unexecuted submission if one is available.

void

shutdown() 

按此前提交任务的执行顺序来有序关闭任务,但不再接受新任务。

Possibly initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted.

List<Runnable>

shutdownNow() 

尝试取消、停止所有任务,并拒绝所有随后提交的任务。

Possibly attempts to cancel and/or stop all tasks, and reject all subsequently submitted tasks.

<T> ForkJoinTask<T>

submit(Callable<T> task) 

提交一个有返回值的任务用于执行,并返回一个可在未来获取任务结果的 Future。

Submits a value-returning task for execution and returns a Future representing the pending results of the task.

<T> ForkJoinTask<T>

submit(ForkJoinTask<T> task) 

提交一个ForkJoinTask 用于执行。

Submits a ForkJoinTask for execution.

ForkJoinTask<?>

submit(Runnable task)

提交一个Runnable 任务用于执行,并返回一个该任务的Future表示。

Submits a Runnable task for execution and returns a Future representing that task.

<T> ForkJoinTask<T>

submit(Runnable task, T result) 

提交一个 Runnable 任务用于执行,并返回一个该任务的 Future表示。

Submits a Runnable task for execution and returns a Future representing that task.

String

toString() 

返回可识别此线程池的字符串及它的状态,包括运行状态、并行级别、工作线程和任务数量。

Returns a string identifying this pool, as well as its state, including indications of run state, parallelism level, and worker and task counts.

 

java.util.concurrent.AbstractExecutorService 继承的方法:

invokeAll,invokeAny,invokeAny

java.lang.Object 继承的方法:

clone,equals,finalize,getClass,hashCode,notify,notifyAll,wait,wait,wait

 

属性描述

defaultForkJoinWorkerThreadFactory

public static final ForkJoinPool.ForkJoinWorkerThreadFactory defaultForkJoinWorkerThreadFactory

Creates a new ForkJoinWorkerThread. This factory is used unless overridden in ForkJoinPool constructors.

创建一个新的ForkJoinWorkerThread。此工厂用于在ForkJoinPool的构造方法中重写。

构造方法描述

ForkJoinPool

public ForkJoinPool()

Creates a ForkJoinPool with parallelism equal toRuntime.availableProcessors(), using thedefault thread factory, no UncaughtExceptionHandler, and non-async LIFO processing mode.

创建一个ForkJoinPool:使用Runtime.availableProcessors()方法获取的数值作为并行级别,使用默认的default thread factory,UncaughtExceptionHandler为空,非异步LIFO模式。

Throws: 

SecurityException - if a security manager exists and the caller is not permitted to modify threads because it does not hold RuntimePermission("modifyThread") 

如果存在security manager,但因调用者未持有RuntimePermission("modifyThread")权限导致不被允许修改线程时,抛出此异常。

ForkJoinPool

public ForkJoinPool(int parallelism)

Creates a ForkJoinPool with the indicated parallelism level, thedefault thread factory, no UncaughtExceptionHandler, and non-async LIFO processing mode.

创建一个ForkJoinPool:使用指定的并行级别,使用默认的default thread factory,UncaughtExceptionHandler为空,非异步LIFO模式。

 

Parameters: 

parallelism - the parallelism level并行级别

Throws: 

IllegalArgumentException - if parallelism less than or equal to zero, or greater than implementation limit

如果并行级别小于等于0 或 大于最高限制时,抛出此异常。

SecurityException - if a security manager exists and the caller is not permitted to modify threads because it does not hold RuntimePermission("modifyThread")

如果存在security manager,但因调用者未持有RuntimePermission("modifyThread")权限导致不被允许修改线程时,抛出此异常。

 

ForkJoinPool

public ForkJoinPool(int parallelism,

ForkJoinPool.ForkJoinWorkerThreadFactory factory,

Thread.UncaughtExceptionHandler handler,boolean asyncMode)

Creates a ForkJoinPool with the given parameters.

使用指定的参数构造ForkJoinPool实例。

Parameters: 

parallelism-the parallelism level. For default value, use Runtime.availableProcessors().

parallelism:默认值为Runtime.availableProcessors()方法获取的cpu数量。

factory - the factory for creating new threads. For default value, usedefaultForkJoinWorkerThreadFactory.

factory:此工厂用于创建线程,默认值为defaultForkJoinWorkerThreadFactory.

handler - the handler for internal worker threads that terminate due to unrecoverable errors encountered while executing tasks. For default value, usenull.

handler:内部工作线程由于在执行期遇到不可恢复的错误被终止时的处理程序,默认值为空。

asyncMode - if true, establishes local first-in-first-out scheduling mode for forked tasks that are never joined. This mode may be more appropriate than default locally stack-based mode in applications in which worker threads only process event-style asynchronous tasks. For default value, usefalse.

asyncMode:如果为true,以先进先出的调度模式的执行未加入的分支任务。在工作线程只处理事件类型异步任务的应用程序中,这种模式可能比默认的本地堆栈模式更合适。默认值为false。

Throws: 

IllegalArgumentException - if parallelism less than or equal to zero, or greater than implementation limit

如果并行级别小于等于0 或 大于最高限制时,抛出此异常。

NullPointerException - if the factory is null

如果线程工厂为空,抛出此异常。

SecurityException - if a security manager exists and the caller is not permitted to modify threads because it does not hold RuntimePermission("modifyThread") 

如果存在security manager,但因调用者未持有RuntimePermission("modifyThread")权限导致不被允许修改线程时,抛出此异常。

 

方法描述

commonPool

public static ForkJoinPool commonPool()

Returns the common pool instance. This pool is statically constructed; its run state is unaffected by attempts toshutdown() orshutdownNow(). However this pool and anyongoing processing are automatically terminated upon programSystem.exit(int). Any program that relies on asynchronous task processing to complete before program termination should invokecommonPool().awaitQuiescence, before exit.

返回common pool实例。此线程池是静态构造的,其运行不受shutdown() shutdownNow()影响,但此线程池和任何不间断运行的任务都将在调用System.exit(int)后自动终止。任何依赖异步任务的程序在未完成任务时应在系统退出前调用commonPool().awaitQuiescence

Returns: 

the common pool instance

common pool实例

Since: 1.8

 

invoke

public <T> T invoke(ForkJoinTask<T> task)

Performs the given task, returning its result upon completion. If the computation encounters an unchecked Exception or Error, it is rethrown as the outcome of this invocation. Rethrown exceptions behave in the same way as regular exceptions, but, when possible, contain stack traces (as displayed for example usingex.printStackTrace()) of both the current thread as well as the thread actually encountering the exception; minimally only the latter.

运行给定任务,完成后返回结果。如果运算时遇到一个未检查异常或错误,它会被重新抛出给调用者。重抛出异常的行为与常规异常处理一致,但在可能的情况下,包含堆栈跟踪(如显式使用ex.printstacktrace())的当前线程及实际发生异常的线程;最低限度的只有后者。

Type Parameters: 

T - the type of the task's result返回结果类型

Parameters: 

task - the task任务

Returns: 

the task's result任务结果

Throws: 

NullPointerException - if the task is null

如果任务为空,抛出此异常。

RejectedExecutionException - if the task cannot be scheduled for execution

如果任务无法被调度执行,抛出此异常。

 

execute

public void execute(ForkJoinTask<?> task)

Arranges for (asynchronous) execution of the given task.

安排(异步)执行给定任务。

Parameters: 

task - the task任务

Throws: 

NullPointerException - if the task is null

如果任务为空,抛出此异常。

RejectedExecutionException - if the task cannot be scheduled for execution

如果任务无法被调度执行,抛出此异常。

 

execute

public void execute(Runnable task)

Description copied from interface: Executor

Executes the given command at some time in the future. The command may execute in a new thread, in a pooled thread, or in the calling thread, at the discretion of theExecutor implementation.

在未来某个时间执行给定的命令。该命令可能在新线程、已入池线程或调用线程中执行,这由 Executor 的具体实现决定。

Parameters: 

task - the runnable task

Throws: 

NullPointerException - if the task is null

如果任务为空,抛出此异常。

RejectedExecutionException - if the task cannot be scheduled for execution

如果任务无法被调度执行,抛出此异常。

 

submit

public <T> ForkJoinTask<T> submit(ForkJoinTask<T> task)

Submits a ForkJoinTask for execution.

提交一个ForkJoinTask 用于执行

Type Parameters: 

T - the type of the task's result任务的返回结果类型

Parameters: 

task - the task to submit待提交的任务

Returns: 

the task

Throws: 

NullPointerException - if the task is null

如果任务为空,抛出此异常。

RejectedExecutionException - if the task cannot be scheduled for execution

如果任务无法被调度执行,抛出此异常。

 

submit

public <T> ForkJoinTask<T> submit(Callable<T> task)

Description copied from interface: ExecutorService

Submits a value-returning task for execution and returns a Future representing the pending results of the task. The Future'sget method will return the task's result upon successful completion.

If you would like to immediately block waiting for a task, you can use constructions of the formresult = exec.submit(aCallable).get();

Note: The Executors class includes a set of methods that can convert some other common closure-like objects, for example,PrivilegedAction toCallable form so they can be submitted.

提交一个有返回值的任务用于执行,并返回一个可在未来获取任务结果的 Future。该 Future 的 get 方法在任务成功完成时将会返回该任务的结果。

如果想立即阻塞任务的等待,则可使用形式构造result=exec.submit(aCallable).get()。

注意:此Executors类包含一组方法,它可以转换成其他一些常见的闭合对象,例如,PrivilegedAction可转换成Callable,因此其可以被提交。

Specified by: 

submit in interface ExecutorService 

Overrides: 

submit in class AbstractExecutorService 

Type Parameters: 

T - the type of the task's result 返回结果类型

Parameters: 

task - the task to submit 待提交的任务

Returns: 

a Future representing pending completion of the task

返回一个可在未来获取任务结果的 Future

Throws: 

NullPointerException - if the task is null

如果任务为空,抛出此异常。

RejectedExecutionException - if the task cannot be scheduled for execution

如果任务无法被调度执行,抛出此异常。

 

submit

public <T> ForkJoinTask<T> submit(Runnable task, T result)

Description copied from interface: ExecutorService

Submits a Runnable task for execution and returns a Future representing that task. The Future'sget method will return the given result upon successful completion.

提交一个 Runnable 任务用于执行,并返回一个表示该任务的 Future。该 Future 的 get 方法在成功完成时将会返回给定的结果。

Specified by: 

submit in interface ExecutorService

Overrides: 

submit in class AbstractExecutorService

Type Parameters: 

T - the type of the result 返回结果类型

Parameters: 

task - the task to submit 待提交的任务

result - the result to return 返回的结果

Returns: 

a Future representing pending completion of the task

返回一个可在未来获取任务结果的 Future

Throws: 

NullPointerException - if the task is null

如果任务为空,抛出此异常。

RejectedExecutionException - if the task cannot be scheduled for execution

如果任务无法被调度执行,抛出此异常。

 

submit

public ForkJoinTask<?> submit(Runnable task)

Description copied from interface: ExecutorService

Submits a Runnable task for execution and returns a Future representing that task. The Future'sget method will returnnull uponsuccessful completion.

提交一个 Runnable 任务用于执行,并返回一个表示该任务的 Future。该 Future 的 get 方法在成功完成时将会返回给定的结果。

Specified by: 

submit in interface ExecutorService 

Overrides: 

submit in class AbstractExecutorService 

Parameters: 

task - the task to submit 提交的任务

Returns: 

a Future representing pending completion of the task

返回一个可在未来获取任务结果的 Future

Throws: 

NullPointerException - if the task is null

如果任务为空,抛出此异常。

RejectedExecutionException - if the task cannot be scheduled for execution

如果任务无法被调度执行,抛出此异常。

 

invokeAll

public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)

Description copied from interface: ExecutorService

Executes the given tasks, returning a list of Futures holding their status and results when all complete.Future.isDone() istrue for each element of the returned list. Note that acompleted task could have terminated either normally or by throwing an exception. The results of this method are undefined if the given collection is modified while this operation is in progress.

执行给定的任务,当所有任务完成时,返回保持任务状态和结果的 Future 列表。返回列表的所有元素的Future.isDone() true时,表示可以正常或通过抛出异常来终止已完成任务。如果正在进行此操作时修改了给定的容器,则此方法的结果是不确定的。

Specified by: 

invokeAll in interface ExecutorService 

Overrides: 

invokeAll in class AbstractExecutorService 

Type Parameters: 

T - the type of the values returned from the tasks 此任务的返回值类型

Parameters: 

tasks - the collection of tasks 任务容器

Returns: 

a list of Futures representing the tasks, in the same sequential order as produced by the iterator for the given task list, each of which has completed

表示任务的 Future 列表,列表顺序与给定任务列表的迭代器所生成的顺序相同,每个任务都已完成。

Throws: 

NullPointerException - if tasks or any of its elements arenull

如果任务列表为空或任意一个列表元素为空,抛出此异常。

RejectedExecutionException - if the task cannot be scheduled for execution

如果任务无法被调度执行,抛出此异常。

 

getFactory

public ForkJoinPool.ForkJoinWorkerThreadFactory getFactory()

Returns the factory used for constructing new workers.

返回用于构造新工作线程的工厂。

Returns: 

the factory used for constructing new workers

用于构造新工作线程的工厂。

 

getUncaughtExceptionHandler

public Thread.UncaughtExceptionHandler getUncaughtExceptionHandler()

Returns the handler for internal worker threads that terminate due to unrecoverable errors encountered while executing tasks.

返回内部工作线程由于在执行任务时因不可恢复的错误而终止时的异常管理器。

Returns: 

the handler, ornull if none

返回异常管理器,如果为空则表示无异常。

 

getParallelism

public int getParallelism()

Returns the targeted parallelism level of this pool.

返回此池的目标并行度。

Returns: 

the targeted parallelism level of this pool

此池的目标并行度。

 

getCommonPoolParallelism

public static int getCommonPoolParallelism()

Returns the targeted parallelism level of the common pool.

返回common pool的目标并行度

Returns: 

the targeted parallelism level of the common pool

返回common pool的目标并行度

Since: 1.8

 

getPoolSize

public int getPoolSize()

Returns the number of worker threads that have started but not yet terminated. The result returned by this method may differ fromgetParallelism() when threads are created to maintain parallelism when others are cooperatively blocked.

返回已经开始但尚未终止的工作线程数。当创建线程以保持并行级别而有其它协同线程阻塞时,此返回结果可能与getParallelism()方法返回的结果不同。

Returns: 

the number of worker threads

工作线程数

 

getAsyncMode

public boolean getAsyncMode()

Returns true if this pool uses local first-in-first-out scheduling mode for forked tasks that are never joined.

当此池为尚未加入的forked tasks采用先进先出调度模式时返回true。

Returns: 

true if this pool uses async mode

返回true为异步模式。

 

getRunningThreadCount

public int getRunningThreadCount()

Returns an estimate of the number of worker threads that are not blocked waiting to join tasks or for other managed synchronization. This method may overestimate the number of running threads.

返回未阻塞等待join task或其他管理同步的工作线程数的估计值,此方法可能高估运行线程的数量。

Returns: 

the number of worker threads

工作线程数

 

getActiveThreadCount

public int getActiveThreadCount()

Returns an estimate of the number of threads that are currently stealing or executing tasks. This method may overestimate the number of active threads.

返回当前正在窃取任务或执行任务的线程数的估计值,此方法可能高估活动线程的数量。

Returns: 

the number of active threads

活动线程数

 

isQuiescent

public boolean isQuiescent()

Returns true if all worker threads are currently idle. An idle worker is one that cannot obtain a task to execute because none are available to steal from other threads, and there are no pending submissions to the pool. This method is conservative; it might not return true immediately upon idleness of all threads, but will eventually become true if threads remain inactive.

返回true时所有线程处于空闲状态。一个空闲工作线程是指未获取到执行任务,因为没有可从其他线程窃取的执行任务,也没有已提交到池的其它任务。这种方法是保守的,可能不会在所有线程空闲时立即返回true,但如果所有线程依然不活动则最终将成为true。

Returns: 

true if all threads are currently idle

返回true时所有线程处于空闲状态。

 

getStealCount

public long getStealCount()

Returns an estimate of the total number of tasks stolen from one thread's work queue by another. The reported value underestimates the actual total number of steals when the pool is not quiescent. This value may be useful for monitoring and tuning fork/join programs: in general, steal counts should be high enough to keep threads busy, but low enough to avoid overhead and contention across threads.

返回一个线程从另一个线程的工作队列中窃取的任务总数的估计值。当此池并非静止状态时报告的实际窃取总数低于真实数据。这个值对于监视和调优fork/join程序可能是有用的:一般来说,窃取计数应该足够高,以保持线程处于忙碌状态,但数值低却可以避免开销和线程间争用。

Returns: 

the number of steals

窃取任务数量估计值

 

getQueuedTaskCount

public long getQueuedTaskCount()

Returns an estimate of the total number of tasks currently held in queues by worker threads (but not including tasks submitted to the pool that have not begun executing). This value is only an approximation, obtained by iterating across all threads in the pool. This method may be useful for tuning task granularities.

返回所有线程的工作队列中的当前任务总数的估计值(但不包括已提交到池但未开始执行的任务)。这只是一个近似值,通过迭代池中的所有线程而得到。对于细粒度的调整来说这种方法可能是有用。

Returns: 

the number of queued tasks

工作队列中的任务总数

 

getQueuedSubmissionCount

public int getQueuedSubmissionCount()

Returns an estimate of the number of tasks submitted to this pool that have not yet begun executing. This method may take time proportional to the number of submissions.

返回已提交到池中但未开始执行的任务数的估计值。此方法可得到时间与提交数量的比例。

Returns: 

the number of queued submissions

已提交任务数

 

hasQueuedSubmissions

public boolean hasQueuedSubmissions()

Returns true if there are any tasks submitted to this pool that have not yet begun executing.

当存在任意任务已提交到池中但未开始执行时返回true。

Returns: 

true if there are any queued submissions

存在排队中的任务时返回true。

 

pollSubmission

protected ForkJoinTask<?> pollSubmission()

Removes and returns the next unexecuted submission if one is available. This method may be useful in extensions to this class that re-assign work in systems with multiple pools.

如果存在下一个未运行的可用的已提交任务,将其返回并在任务队列中删除。当系统中存在多个线程池时,此方法或许对于此类的扩展类在进行作业重新分配时是有用的。

Returns: 

the next submission, ornull if none

下一个已提交任务,如果没有任务则返回null

 

drainTasksTo

protected int drainTasksTo(Collection<? superForkJoinTask<?>> c)

Removes all available unexecuted submitted and forked tasks from scheduling queues and adds them to the given collection, without altering their execution status. These may include artificially generated or wrapped tasks. This method is designed to be invoked only when the pool is known to be quiescent. Invocations at other times may not remove all tasks. A failure encountered while attempting to add elements to collectionc may result in elements being in neither, either or both collections when the associated exception is thrown. The behavior of this operation is undefined if the specified collection is modified while the operation is in progress.

从调度队列删除所有可用的且未提交执行的fork task,并将它们添加到给定的集合,而不改变其执行状态,包括人工生成或包装类。此方法被设计为仅在已知池为静态时才可被调用。其它时候调用可能不会删除所有任务。当将元素添加到集合C时失败,可能导致关联异常被抛出时,元素不在两个集合中。如果在操作过程中,指定的集合已被修改,则此操作的行为是未定义的。

Parameters: 

c - the collection to transfer elements into

转移元素的目标容器

Returns: 

the number of elements transferred

转移元素的数量

 

toString

public String toString()

Returns a string identifying this pool, as well as its state, including indications of run state, parallelism level, and worker and task counts.

返回可识别此线程池的字符串及它的状态,包括运行状态、并行级别、工作线程和任务数量。

Overrides: 

toString in class Object重写Object的toString方法

Returns: 

a string identifying this pool, as well as its state

可识别此线程池的字符串及它的状态

 

shutdown

public void shutdown()

Possibly initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted. Invocation has no effect on execution state if this is thecommonPool(), and no additional effect if already shut down. Tasks that are in the process of being submitted concurrently during the course of this method may or may not be rejected.

可能开始有序关闭此前提交的任务,但不再接受新任务。如果是通过commonpool()调用获取到的common pool,那么对其执行状态没有影响。如果此池已经关闭再次调用此方法不会有额外影响。此方法执行过程中同时提交的任务可能被拒绝或不被拒绝。

Throws: 

SecurityException - if a security manager exists and the caller is not permitted to modify threads because it does not hold RuntimePermission("modifyThread")

如果存在security manager,但因调用者未持有RuntimePermission("modifyThread")权限导致不被允许修改线程时,抛出此异常。

 

shutdownNow

public List<Runnable> shutdownNow()

Possibly attempts to cancel and/or stop all tasks, and reject all subsequently submitted tasks. Invocation has no effect on execution state if this is thecommonPool(), and no additional effect if already shut down. Otherwise, tasks that are in the process of being submitted or executed concurrently during the course of this method may or may not be rejected. This method cancels both existing and unexecuted tasks, in order to permit termination in the presence of task dependencies. So the method always returns an empty list (unlike the case for some other Executors).

可能尝试取消或停止所有任务,并拒绝所有随后提交的任务。如果是通过commonpool()调用获取到的common pool,那么对其执行状态没有影响。如果此池已经关闭再次调用此方法不会有额外影响。此方法执行过程中同时提交的任务可能被拒绝或不被拒绝。此方法取消现有的和未完成的任务,以便在有相关任务时正常终止,所以该方法总是返回一个空列表(这一点与其他一些Executors不同)。

Returns: 

an empty list空列表

Throws: 

SecurityException - if a security manager exists and the caller is not permitted to modify threads because it does not hold RuntimePermission("modifyThread")

如果存在security manager,但因调用者未持有RuntimePermission("modifyThread")权限导致不被允许修改线程时,抛出此异常。

 

isTerminated

public boolean isTerminated()

Returns true if all tasks have completed following shut down.

如果此池关闭后所有任务已停止,返回true

Returns: 

true if all tasks have completed following shut down

如果此池关闭后所有任务已停止,返回true

 

isTerminating

public boolean isTerminating()

Returns true if the process of termination has commenced but not yet completed. This method may be useful for debugging. A return oftrue reported a sufficient period after shutdown may indicate that submitted tasks have ignored or suppressed interruption, or are waiting for I/O, causing this executor not to properly terminate. (See the advisory notes for classForkJoinTask stating that tasks should not normally entail blocking operations. But if they do, they must abort them on interrupt.)

如果终止过程已开始,但尚未完成,则返回true。此方法对于调试来说可能是有用的。如果此池执行关闭操作的充分时间后依然返回true,可能表示提交的任务忽略或抑制了中断,或正在等待I / O,造成此executor 无法正常终止。(见类forkjointask的说明,任务通常不需要阻塞操作,但如非要这样做,他们必须清除它们的中断。)

Returns: 

true if terminating but not yet terminated

如果终止过程已开始,但尚未完成,则返回true。

 

isShutdown

public boolean isShutdown()

Returns true if this pool has been shut down.

如果此池已关闭返回true。

Returns: 

true if this pool has been shut down

如果此池已关闭返回true。

 

awaitTermination

public boolean awaitTermination(long timeout, TimeUnit unit) throwsInterruptedException

Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first. Because thecommonPool() never terminates until program shutdown, when applied to the common pool, this method is equivalent toawaitQuiescence(long, TimeUnit) but always returnsfalse.

阻塞直到所有任务执行完成。此池收到关闭请求、执行超时、当前线程已中断,任意一种情况先发生都将返回。因为commonPool()在程序关闭前不会终止,所以当请求阻塞的是common pool,此方法与awaitQuiescence(long, TimeUnit)等价,但总是会返回false。

Parameters: 

timeout - the maximum time to wait最大等待时间

unit - the time unit of the timeout argument时间单位

Returns: 

true if this executor terminated andfalse if the timeout elapsed before termination

如果此executor已终止,返回true;如果此池超过最大等待时间仍未终止,返回false。

Throws: 

InterruptedException - if interrupted while waiting

如果在等待终止过程中发生中断,抛出此异常。

 

awaitQuiescence

public boolean awaitQuiescence(long timeout,TimeUnit unit)

If called by a ForkJoinTask operating in this pool, equivalent in effect toForkJoinTask.helpQuiesce(). Otherwise, waits and/or attempts to assist performing tasks until this poolisQuiescent() or the indicated timeout elapses.

如果此方法被此池中的Forkjointask调用,其作用与ForkJoinTask.helpQuiesce()等价。否则,等待或试图帮助完成任务,直到这个池的所有工作线程处于空闲时(isQuiescent())或超时返回。

Parameters: 

timeout - the maximum time to wait最大等待时间

unit - the time unit of the timeout argument时间单位

Returns: 

true if quiescent;false if the timeout elapsed.

如果池中所有线程已处于空闲状态,返回true;如果超时返回false。

 

managedBlock

public static void managedBlock(ForkJoinPool.ManagedBlocker blocker) throwsInterruptedException

Runs the given possibly blocking task. Whenrunning in a ForkJoinPool, this method possibly arranges for a spare thread to be activated if necessary to ensure sufficient parallelism while the current thread is blocked inblocker.block().

This method repeatedly callsblocker.isReleasable() andblocker.block() until either method returnstrue. Every call toblocker.block() is preceded by a call toblocker.isReleasable() that returnedfalse.

If not running in a ForkJoinPool, this method is behaviorally equivalent to

while (!blocker.isReleasable())

    if (blocker.block())

    break;

If running in a ForkJoinPool, the pool may first be expanded to ensure sufficient parallelism available during the call toblocker.block().

运行给定的可能发生阻塞的任务。当此任务运行在ForkJoinPool时,当前线程如果调用blocker.block()被阻塞,为了保证足够的并行性,此方法可能会使用一个空闲线程去激活。

该方法重复调用blocker.isReleasable() andblocker.block()直到任意一个方法返回true。每次调用blocker.block()之前调用blocker.isReleasable()将返回false。

如果是运行在非ForkJoinPool,此方法等价于如下代码:

while (!blocker.isReleasable())

    if (blocker.block())

    break;

如果是运行在ForkJoinPool,当调用blocker.block()方法时,此池为了保持足够的并行性可能会扩大线程池。

Parameters: 

blocker - the blocker task可阻塞任务

Throws: 

InterruptedException - ifblocker.block() did so

如果执行blocker.block()方法,可能抛出此异常。

 

newTaskFor

protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value)

Description copied from class: AbstractExecutorService

Returns a RunnableFuture for the given runnable and default value.

返回给定runnable任务和给定值的RunnableFuture

Overrides: 

newTaskFor in class AbstractExecutorService

Type Parameters:

T - the type of the given value值类型

Parameters:

runnable - the runnable task being wrappedrunnable任务

value - the default value for the returned future默认值

Returns:

a RunnableFuture which, when run, will run the underlying runnable and which, as aFuture, will yield the given value as its result and provide for cancellation of the underlying task

一个 RunnableFuture运行期间,执行底层runnable任务;但在未来给定值作为结果,并为底层任务提供取消操作

 

newTaskFor

protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable)

Description copied from class: AbstractExecutorService

Returns a RunnableFuture for the given callable task.

返回给定callable 任务的RunnableFuture

Overrides:

newTaskFor in class AbstractExecutorService

Type Parameters:

T - the type of the callable's result返回结果类型

Parameters:

callable - the callable task being wrapped被包装的callable任务

Returns:

a RunnableFuture which, when run, will call the underlying callable and which, as aFuture, will yield the callable's result as its result and provide for cancellation of the underlying task

一个 RunnableFuture运行期间,执行底层callable任务;但在未来返回callable任务的结果,并为底层任务提供取消操作

0 0