您的位置:首页 > 编程语言 > Java开发

Fork/Join(4):ForkJoinTask之API翻译

2016-12-31 00:00 309 查看
摘要: 上一节翻译了ForkJoinPool的API,这一节翻译另外一个核心类ForkJoinTask的API。

译者:Xcafe 编辑日期:20161231 博客:https://my.oschina.net/xcafe

上一节翻译了ForkJoinPool的API,这一节翻译另外一个核心类ForkJoinTask的API。

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

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

以下为翻译内容:

public abstract class ForkJoinTask<V>

extends Object implements Future<V>, Serializable

Abstract base class for tasks that run within a ForkJoinPool. A ForkJoinTask is a thread-like entity that is much lighter weight than a normal thread. Huge numbers of tasks and subtasks may be hosted by a small number of actual threads in a ForkJoinPool, at the price of some usage limitations.

A "main" ForkJoinTask begins execution when it is explicitly submitted to a ForkJoinPool, or, if not already engaged in a ForkJoin computation, commenced in the ForkJoinPool.commonPool() via fork(), invoke(), or related methods. Once started, it will usually in turn start other subtasks. As indicated by the name of this class, many programs using ForkJoinTask employ only methods fork() and join(), or derivatives such as invokeAll. However, this class also provides a number of other methods that can come into play in advanced usages, as well as extension mechanics that allow support of new forms of fork/join processing.

这是运行于ForkJoinPool的任务的抽象基类。一个ForkJoinTask是类线程实体,但比普通线程要轻量得多。巨大数量的任务和子任务可以由ForkJoinPool的少量实际线程托管,但需承受一些使用限制。

“main”ForkJoinTask在其明确提交到一个ForkJoinPool时开始执行;如果还未进行forkjoin计算,可通过ForkJoinPool.commonPool() 的fork(), invoke(), 或相关的方法开始执行。一旦开始,它通常会启动其它子任务。如类名所示,许多程序使用Forkjointask时只使用方法fork()和join(),或其衍生方法如invokeAll。然而,此类还提供了许多高级用法,以扩展支持新形式的fork/join处理。

A ForkJoinTask is a lightweight form of Future. The efficiency of ForkJoinTasks stems from a set of restrictions (that are only partially statically enforceable) reflecting their main use as computational tasks calculating pure functions or operating on purely isolated objects. The primary coordination mechanisms are fork(), that arranges asynchronous execution, and join(), that doesn't proceed until the task's result has been computed. Computations should ideally avoid synchronized methods or blocks, and should minimize other blocking synchronization apart from joining other tasks or using synchronizers such as Phasers that are advertised to cooperate with fork/join scheduling. Subdividable tasks should also not perform blocking I/O, and should ideally access variables that are completely independent of those accessed by other running tasks. These guidelines are loosely enforced by not permitting checked exceptions such as IOExceptions to be thrown. However, computations may still encounter unchecked exceptions, that are rethrown to callers attempting to join them. These exceptions may additionally include RejectedExecutionException stemming from internal resource exhaustion, such as failure to allocate internal task queues. Rethrown exceptions behave in the same way as regular exceptions, but, when possible, contain stack traces (as displayed for example using ex.printStackTrace()) of both the thread that initiated the computation as well as the thread actually encountering the exception; minimally only the latter.

Forkjointask是一个轻量级形式的Future。forkjointasks效率源于一组限制(只能部分静态强制执行)反映其主要用途为纯函数计算或对纯粹独立的对象进行操作。主要的协调机制fork()用于安排异步执行,join()操作需等到已经计算出任务结果。理论上来说计算应尽可能避免同步方法或同步块,除加入任务外应最小化其它阻塞同步,或者使用同步器,譬如宣布可以与fork/join调度协作的Phasers。可再分任务也不应该执行阻塞I/O,访问变量应完全独立于其他正在运行的任务。通过不允许抛出检查型异常(如IOExceptions),这些准则被宽松地执行。但计算时仍然可能遇到非检查异常,这些异常会试图重新抛出给调用者。这些异常还包括当内部资源枯竭时抛出RejectedExecutionException(例如分配内部任务队列失败)。重抛出异常的行为与常规异常一致,但如果可能,包含启动计算的线程及实际发生异常的线程的堆栈跟踪信息(如显式使用ex.printstacktrace()),但至少会有后者。

It is possible to define and use ForkJoinTasks that may block, but doing do requires three further considerations: (1) Completion of few if any other tasks should be dependent on a task that blocks on external synchronization or I/O. Event-style async tasks that are never joined (for example, those subclassing CountedCompleter) often fall into this category. (2) To minimize resource impact, tasks should be small; ideally performing only the (possibly) blocking action. (3) Unless the ForkJoinPool.ManagedBlocker API is used, or the number of possibly blocked tasks is known to be less than the pool's ForkJoinPool.getParallelism() level, the pool cannot guarantee that enough threads will be available to ensure progress or good performance.

可以定义和使用可能阻塞的ForkJoinTasks,但这样做需要进一步考虑三个因素:(1)完成一些任何其他任务时,应该依赖可阻止外部同步或I/O的任务,从不join操作的事件式异步任务通常属于此类别(例如这些子类:CountedCompleter)。(2)为了尽量减少资源影响,任务应尽可能小且最好只执行(可能)阻塞任务。(3)除非使用ForkJoinPool.ManagedBlocker 接口,或者阻塞任务数少于ForkJoinPool.getParallelism()获取到的并行数,否则此池无法保证有足够的线程可用于确保执行和高性能。

The primary method for awaiting completion and extracting results of a task is join(), but there are several variants: The Future.get() methods support interruptible and/or timed waits for completion and report results using Future conventions. Method invoke() is semantically equivalent to fork(); join() but always attempts to begin execution in the current thread. The "quiet" forms of these methods do not extract results or report exceptions. These may be useful when a set of tasks are being executed, and you need to delay processing of results or exceptions until all complete. Method invokeAll (available in multiple versions) performs the most common form of parallel invocation: forking a set of tasks and joining them all.

join()是等待完成任务并获取结果的主要方法,但有几个变型:Future.get()方法支持使用Future进行中断和定时等待任务完成并报告结果。invoke()方法的语义等同于fork(),但join()总是试图在当前线程开始执行。

这些方法的“静默”形式不提取结果或报告异常,这可能在一组任务被执行时很有用,假如您需要直到所有任务完成时才获取结果或处理异常。Invokeall方法(有多个版本)是执行并行调用的最常见形式:分解一组任务并加入这些任务。

In the most typical usages, a fork-join pair act like a call (fork) and return (join) from a parallel recursive function. As is the case with other forms of recursive calls, returns (joins) should be performed innermost-first. For example, a.fork(); b.fork(); b.join(); a.join(); is likely to be substantially more efficient than joining a before b.

在最典型的用法中,一对fork-join的行为就像一个调用(fork)和从一个并行递归函数中返回(join)。与其它形式的递归调用一样,返回(join)应该在最内层进行。例如:a.fork(); b.fork(); b.join(); a.join(); 可能比a.join()在b.join()之前执行更有效率。

The execution status of tasks may be queried at several levels of detail: isDone() is true if a task completed in any way (including the case where a task was cancelled without executing); isCompletedNormally() is true if a task completed without cancellation or encountering an exception; isCancelled() is true if the task was cancelled (in which case getException() returns a CancellationException); and isCompletedAbnormally() is true if a task was either cancelled or encountered an exception, in which case getException() will return either the encountered exception or CancellationException.

任务执行状态可在多个详情级别查询:isDone()返回true,表示一个任务以任意方式结束(包括任务被取消而未执行);isCompletedNormally()返回true,表示一个任务在没有取消和遇到异常的情况下正常完成;isCancelled()返回true,表示此任务被取消(此情况下,getException()方法返回CancellationException);isCompletedAbnormally()返回true,表示一个任务被取消或发生异常,此情况下,getException()方法将返回遇到的异常或CancellationException。

The ForkJoinTask class is not usually directly subclassed. Instead, you subclass one of the abstract classes that support a particular style of fork/join processing, typically RecursiveAction for most computations that do not return results, RecursiveTask for those that do, and CountedCompleter for those in which completed actions trigger other actions. Normally, a concrete ForkJoinTask subclass declares fields comprising its parameters, established in a constructor, and then defines a compute method that somehow uses the control methods supplied by this base class.

ForkJoinTask类通常不用于直接继承。相反,你应该子类化一个支持特定用途的fork/join处理抽象类:RecursiveAction 通常用于大多数无需返回结果的计算,RecursiveTask也可用于这些,CountedCompleter则用于在完成动作时触发其他操作。通常,一个具体的ForkJoinTask子类声明包含其在构造函数中的参数字段,然后定义一个compute方法,该方法以某种形式使用该基类提供的控制方法。

Method join() and its variants are appropriate for use only when completion dependencies are acyclic; that is, the parallel computation can be described as a directed acyclic graph (DAG). Otherwise, executions may encounter a form of deadlock as tasks cyclically wait for each other. However, this framework supports other methods and techniques (for example the use of Phaser, helpQuiesce(), and complete(V)) that may be of use in constructing custom subclasses for problems that are not statically structured as DAGs. To support such usages, a ForkJoinTask may be atomically tagged with a short value using setForkJoinTaskTag(short) or compareAndSetForkJoinTaskTag(short, short) and checked using getForkJoinTaskTag(). The ForkJoinTask implementation does not use these protected methods or tags for any purpose, but they may be of use in the construction of specialized subclasses. For example, parallel graph traversals can use the supplied methods to avoid revisiting nodes/tasks that have already been processed. (Method names for tagging are bulky in part to encourage definition of methods that reflect their usage patterns.)

join()方法及其变型适合仅在完成依赖关系是非循环时使用,即并行计算可以被描述为有向无环图(DAG)。否则,执行器可能遇到某种形式的死锁,因为任务循环等待彼此。然而,该框架支持的其他方法和技术(例如Phaser, helpQuiesce() 和complete(V)),这些自定义子类的构建,可能会带来非静态结构的DAGs的问题。为了支持这些用法,ForkJoinTask 可使用setForkJoinTaskTag(short) 或compareAndSetForkJoinTaskTag(short, short)以short值类型进行原子标记,并使用getForkJoinTaskTag()进行检查。此ForkJoinTask实现未将这些protected 方法或标签用于任何目的,但它们可能用于构建专门的子类。例如,并行图遍历可以使用提供的方法来避免重新访问已经处理的节点/任务。 (标记的方法名称部分是笨重的,以鼓励定义反映其使用模式的方法。)

Most base support methods are final, to prevent overriding of implementations that are intrinsically tied to the underlying lightweight task scheduling framework. Developers creating new basic styles of fork/join processing should minimally implement protected methods exec(), setRawResult(V), and getRawResult(), while also introducing an abstract computational method that can be implemented in its subclasses, possibly relying on other protected methods provided by this class.

大部分基础支持方法是final修饰的,以防止覆盖本质上绑定到底层轻量级任务调度框架的实现。创建新fork/join处理基本类型的开发者至少应该实现protected方法exec()、setRawResult(V)和getRawResult();同时还引入了一个可在子类中实现的抽象计算方法,此方法的实现可能依赖于这个类提供的其它protected 方法。

ForkJoinTasks should perform relatively small amounts of computation. Large tasks should be split into smaller subtasks, usually via recursive decomposition. As a very rough rule of thumb, a task should perform more than 100 and less than 10000 basic computational steps, and should avoid indefinite looping. If tasks are too big, then parallelism cannot improve throughput. If too small, then memory and internal task maintenance overhead may overwhelm processing.

ForkJoinTasks 应为相对小型的计算。大任务应拆分成更小的子任务,通常使用递归进行分解。作为非常粗略的经验法则,单个任务的基本计算步骤数最好大于100并小于10000,并应避免不确定的循环。如果任务太大,则无法利用并行提高吞吐量;如果太小,则内存和内部任务维护开销可能超过任务处理开销。

This class provides adapt methods for Runnable and Callable, that may be of use when mixing execution of ForkJoinTasks with other kinds of tasks. When all tasks are of this form, consider using a pool constructed in asyncMode.

ForkJoinTasks are Serializable, which enables them to be used in extensions such as remote execution frameworks. It is sensible to serialize tasks only before or after, but not during execution. Serialization is not relied on during execution itself.

此类提供了适配Runnable 和Callable任务的方法,这可能用于混合执行ForkJoinTasks及其他类型任务。当所有任务都需要混合执行,请考虑异步模式的池(asyncMode)。

ForkJoinTasks 是可序列化的,这使得其可用于扩展,如远程执行框架。正确序列化的方式是在任务执行前和执行后,而不是在执行期间。任务自身在执行过程中不依赖于序列化。

Since:1.7

See Also:

Serialized Form

构造方法摘要

Constructors
Constructor and Description
ForkJoinTask()

方法摘要

All MethodsStatic Methods Instance Methods Abstract Methods Concrete Methods
Modifier and Type
Method and Description
static <T> ForkJoinTask<T>
adapt(Callable<? extends T> callable)
返回一个新的ForkJoinTask。当其被运行时执行给定的Callable 对象的call方法,执行join()方法时返回运行结果,期间遇到的任何检查型异常都将转换为RuntimeException。
Returns a new ForkJoinTask that performs the call method of the given Callable as its action, and returns its result upon join(), translating any checked exceptions encountered into RuntimeException.
static ForkJoinTask<?>
adapt(Runnable runnable)
返回一个新的ForkJoinTask。当其被运行时执行给定的Runnable对象的run方法,执行join()方法时返回null。
Returns a new ForkJoinTask that performs the run method of the given Runnable as its action, and returns a null result upon join().
static <T> ForkJoinTask<T>
adapt(Runnable runnable, T result)
返回一个新的ForkJoinTask。当其被运行时执行给定的Runnable对象的run方法,执行join()方法时返回预给定结果。
Returns a new ForkJoinTask that performs the run method of the given Runnable as its action, and returns the given result upon join().
boolean
cancel(boolean mayInterruptIfRunning)
尝试取消此任务的执行
Attempts to cancel execution of this task.
boolean
compareAndSetForkJoinTaskTag(short e, short tag)
使用原子操作设定任务标签
Atomically conditionally sets the tag value for this task.
void
complete(V value)
完成此任务,如果任务未中止或取消则返回给定值作为结果给join或相关操作的后续调用
Completes this task, and if not already aborted or cancelled, returning the given value as the result of subsequent invocations of join and related operations.
void
completeExceptionally(Throwable ex)
以异常方式结束此任务,如果任务未中止或取消,则使其在join和相关操作时抛出给定异常。
Completes this task abnormally, and if not already aborted or cancelled, causes it to throw the given exception upon join and related operations.
protected abstract boolean
exec()
立即执行此任务的基础操作,当此方法返回时结果为true,该任务将保证已经正常完成。
Immediately performs the base action of this task and returns true if, upon return from this method, this task is guaranteed to have completed normally.
ForkJoinTask<V>
fork()
安排异步执行此任务。如果适用,安排其在此任务正在运行的线程池中执行;否则,如果inForkJoinPool()方法返回false,则安排其在ForkJoinPool.commonPool()中执行。
Arranges to asynchronously execute this task in the pool the current task is running in, if applicable, or using the ForkJoinPool.commonPool() if not inForkJoinPool().
V
get()
等待必要的计算完成,然后获取其结果。
Waits if necessary for the computation to complete, and then retrieves its result.
V
get(long timeout, TimeUnit unit)
在给定时间内等待必要的计算完成,然后获取其可用的结果。
Waits if necessary for at most the given time for the computation to complete, and then retrieves its result, if available.
Throwable
getException()
返回来自于基础计算的异常,或任务取消后的CancellationException,或任务尚未完成时返回null。
Returns the exception thrown by the base computation, or a CancellationException if cancelled, or null if none or if the method has not yet completed.
short
getForkJoinTaskTag()
返回此任务的标签。
Returns the tag for this task.
static ForkJoinPool
getPool()
返回此任务的执行线程池,如果此任务在非ForkJoinPool中执行则返回null。
Returns the pool hosting the current task execution, or null if this task is executing outside of any ForkJoinPool.
static int
getQueuedTaskCount()
返回已被当前工作线程执行fork操作但尚未执行的任务数的估计值。
Returns an estimate of the number of tasks that have been forked by the current worker thread but not yet executed.
abstract V
getRawResult()
join()方法返回的结果(即使这个任务完成异常),如果这项任务未知是否已完成则返回null
Returns the result that would be returned by join(), even if this task completed abnormally, or null if this task is not known to have been completed.
static int
getSurplusQueuedTaskCount()
返回当前工作线程的队列中正在排队的任务的估计值(其它工作线程可窃取的任务);如果当前线程并不是ForkJoinPool中的线程则返回0。
Returns an estimate of how many more locally queued tasks are held by the current worker thread than there are other worker threads that might steal them, or zero if this thread is not operating in a ForkJoinPool.
static void
helpQuiesce()
可能直到池托管的当前任务不活动时才再开始执行任务
Possibly executes tasks until the pool hosting the current task is quiescent.
static boolean
inForkJoinPool()
如果当前线程是ForkJoinWorkerThread并且以ForkJoinPool运算的方式执行则返回true。
Returns true if the current thread is a ForkJoinWorkerThread executing as a ForkJoinPool computation.
V
invoke()
开始执行此任务,如果有必要则等待它完成。返回结果或抛出一个(非检查) RuntimeException 或 Error(如果底层运算出现这样的操作)
Commences performing this task, awaits its completion if necessary, and returns its result, or throws an (unchecked) RuntimeException or Error if the underlying computation did so.
static <T extends ForkJoinTask<?>>
Collection<T>
invokeAll(Collection<T> tasks)
Fork执行给定容器中的所有任务,当所有任务结束时或遇到异常时返回(此情况下会重新抛出异常)
Forks all tasks in the specified collection, returning when isDone holds for each task or an (unchecked) exception is encountered, in which case the exception is rethrown.
static void
invokeAll(ForkJoinTask<?>... tasks)
Fork执行给定的所有任务,当所有任务结束时或遇到异常时返回(此情况下会重新抛出异常)
Forks the given tasks, returning when isDone holds for each task or an (unchecked) exception is encountered, in which case the exception is rethrown.
static void
invokeAll(ForkJoinTask<?> t1, ForkJoinTask<?> t2)
Fork执行给定的两个任务,当所有任务结束时或遇到异常时返回(此情况下会重新抛出异常)
Forks the given tasks, returning when isDone holds for each task or an (unchecked) exception is encountered, in which case the exception is rethrown.
boolean
isCancelled()
如果此任务在正常完成前被取消,返回true。
Returns true if this task was cancelled before it completed normally.
boolean
isCompletedAbnormally()
如果此任务抛出异常或被取消,返回true。
Returns true if this task threw an exception or was cancelled.
boolean
isCompletedNormally()
如果此任务正常完成且未抛异常且未被取消,返回true。
Returns true if this task completed without throwing an exception and was not cancelled.
boolean
isDone()
如果任务已结束返回true。
Returns true if this task completed.
V
join()
当任务结束时返回计算结果。
Returns the result of the computation when it is done.
protected static ForkJoinTask<?>
peekNextLocalTask()
返回位于当前线程的任务队列但还未执行过的可立即执行的任务,但不取消计划或执行。
Returns, but does not unschedule or execute, a task queued by the current thread but not yet executed, if one is immediately available.
protected static ForkJoinTask<?>
pollNextLocalTask()
取消执行计划并返回:并非正在执行的且位于当前线程的下一个任务队列中但还未被执行的任务(如果当前线程位于ForkJoinPool)。
Unschedules and returns, without executing, the next task queued by the current thread but not yet executed, if the current thread is operating in a ForkJoinPool.
protected static ForkJoinTask<?>
pollTask()
如果当前线程位于ForkJoinPool,取消执行计划并返回:非正在执行的任务,位于当前线程的下一个任务队列中但还未被执行的可用任务。如果无可用任务,任务可能已经被其它线程执行fork操作。
If the current thread is operating in a ForkJoinPool, unschedules and returns, without executing, the next task queued by the current thread but not yet executed, if one is available, or if not available, a task that was forked by some other thread, if available.
void
quietlyComplete()
以正常方式完成此任务且不设置值。
Completes this task normally without setting a value.
void
quietlyInvoke()
以静默方式开始执行此任务并等待任务结束,但不返回其结果或抛出异常。
Commences performing this task and awaits its completion if necessary, without returning its result or throwing its exception.
void
quietlyJoin()
以静默方式执行此任务的join操作,但不返回其结果或抛出异常。
Joins this task, without returning its result or throwing its exception.
void
reinitialize()
重置此任务内部簿记状态以允许后续fork操作。
Resets the internal bookkeeping state of this task, allowing a subsequent fork.
short
setForkJoinTaskTag(short tag)
以原子操作的方式设置此任务的标记。
Atomically sets the tag value for this task.
protected abstract void
setRawResult(V value)
强制以给定值作为返回结果。
Forces the given value to be returned as a result.
boolean
tryUnfork()
尝试取消此任务执行。
Tries to unschedule this task for execution.

java.lang.Object继承的方法

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

构造方法详情

ForkJoinTask

public ForkJoinTask()

方法详情

fork

public final ForkJoinTask<V> fork()

Arranges to asynchronously execute this task in the pool the current task is running in, if applicable, or using the ForkJoinPool.commonPool() if not inForkJoinPool(). While it is not necessarily enforced, it is a usage error to fork a task more than once unless it has completed and been reinitialized. Subsequent modifications to the state of this task or any data it operates on are not necessarily consistently observable by any thread other than the one executing it unless preceded by a call to join() or related methods, or a call to isDone() returning true.

安排在此任务正在运行的线程池中异步执行此任务。如果common pool可用则使用ForkJoinPool.commonPool(),否则使用 inForkJoinPool()。当其无需强制执行,多次fork同一个任务是错误的用法,除非它已完成并被重新初始化。对此任务的状态或其运行的任何数据的后续修改,其它线程观察到的可能并不一致,除非先调用join()或相关方法,并且调用isDone()时已经返回true。

Returns:

this, to simplify usage

join

public final V join()

Returns the result of the computation when it is done. This method differs from get() in that abnormal completion results in RuntimeException or Error, not ExecutionException, and that interrupts of the calling thread do not cause the method to abruptly return by throwing InterruptedException.

当完成时返回计算结果。此方法与get()方法不同在于非正常结束时的结果:RuntimeException和 Error(不包括ExecutionException),并且中断调用线程不会导致此方法突然返回并抛出InterruptedException。

Returns:

the computed result 运算结果

invoke

public final V invoke()

Commences performing this task, awaits its completion if necessary, and returns its result, or throws an (unchecked) RuntimeException or Error if the underlying computation did so.

开始执行此任务,如果有必要则等待它完成,返回结果或抛出一个(非检查) RuntimeException 或 Error(如果底层运算出现这样的操作)

Returns:

the computed result 运算结果

invokeAll

public static void invokeAll(ForkJoinTask<?> t1, ForkJoinTask<?> t2)

Forks the given tasks, returning when isDone holds for each task or an (unchecked) exception is encountered, in which case the exception is rethrown. If more than one task encounters an exception, then this method throws any one of these exceptions. If any task encounters an exception, the other may be cancelled. However, the execution status of individual tasks is not guaranteed upon exceptional return. The status of each task may be obtained using getException() and related methods to check if they have been cancelled, completed normally or exceptionally, or left unprocessed.

Fork执行给定的两个任务,当所有任务结束时或遇到非检查异常时返回(此情况下会重新抛出异常)。如果超过一个任务发生异常,此方法将任意抛出其中一个异常。如果任一任务遇到异常,另外一个任务可能会被取消,但个别任务的状态不保证一定会返回。如果这些任务被取消、正常完成、或异常,或离开未处理,每个任务的状态可以使用getException()或相关方法去检查。

Parameters:

t1 - the first task

t2 - the second task

Throws:

NullPointerException - if any task is null

如果任意任务为null,抛出NullPointerException。

invokeAll

public static void invokeAll(ForkJoinTask<?>... tasks)

Forks the given tasks, returning when isDone holds for each task or an (unchecked) exception is encountered, in which case the exception is rethrown. If more than one task encounters an exception, then this method throws any one of these exceptions. If any task encounters an exception, others may be cancelled. However, the execution status of individual tasks is not guaranteed upon exceptional return. The status of each task may be obtained using getException() and related methods to check if they have been cancelled, completed normally or exceptionally, or left unprocessed.

Fork执行给定的所有任务,当所有任务结束时或遇到非检查异常时返回(此情况下会重新抛出异常)。如果超过一个任务发生异常,此方法将任意抛出其中一个异常。如果任一任务遇到异常,另外一个任务可能会被取消,但个别任务的状态不保证一定会返回。如果这些任务被取消、正常完成、或异常,或离开未处理,每个任务的状态可以使用getException()或相关方法去检查。

Parameters:

tasks - the tasks

Throws:

NullPointerException - if any task is null

如果任意任务为null,抛出NullPointerException。

invokeAll

public static <T extends ForkJoinTask<?>> Collection<T> invokeAll(Collection<T> tasks)

Forks all tasks in the specified collection, returning when isDone holds for each task or an (unchecked) exception is encountered, in which case the exception is rethrown. If more than one task encounters an exception, then this method throws any one of these exceptions. If any task encounters an exception, others may be cancelled. However, the execution status of individual tasks is not guaranteed upon exceptional return. The status of each task may be obtained using getException() and related methods to check if they have been cancelled, completed normally or exceptionally, or left unprocessed.

Fork执行给定容器的所有任务,当所有任务结束时或遇到非检查异常时返回(此情况下会重新抛出异常)。如果超过一个任务发生异常,此方法将任意抛出其中一个异常。如果任一任务遇到异常,另外一个任务可能会被取消,但个别任务的状态不保证一定会返回。如果这些任务被取消、正常完成、或异常,或离开未处理,每个任务的状态可以使用getException()或相关方法去检查。

Type Parameters:

T - the type of the values returned from the tasks 给定任务的结果类型

Parameters:

tasks - the collection of tasks 任务容器

Returns:

the tasks argument, to simplify usage

Throws:

NullPointerException - if tasks or any element are null

如果任意任务或元素为null,抛出NullPointerException。

cancel

public boolean cancel(boolean mayInterruptIfRunning)

Attempts to cancel execution of this task. This attempt will fail if the task has already completed or could not be cancelled for some other reason. If successful, and this task has not started when cancel is called, execution of this task is suppressed. After this method returns successfully, unless there is an intervening call to reinitialize(), subsequent calls to isCancelled(), isDone(), and cancel will return true and calls to join() and related methods will result in CancellationException.

This method may be overridden in subclasses, but if so, must still ensure that these properties hold. In particular, the cancel method itself must not throw exceptions.

This method is designed to be invoked by other tasks. To terminate the current task, you can just return or throw an unchecked exception from its computation method, or invoke completeExceptionally(Throwable).

尝试取消此任务。如果此任务已经被取消或者因为某些原因无法取消,那么此尝试将失败。如果成功,并且在取消调用时此任务还未启动,则会抑制此任务的执行。当此方法返回成功后,除非调用reinitialize()进行干预,否则随后调用isCancelled()、isDone()和cancel方法都将返回true,调用join()和其相关方法将返回CancellationException结果。

此方法如果被子类重写,则仍然必须确保这些属性。特别强调,cancel方法本身不能抛出异常。

此方法设计为被其他任务调用。如果要终止当前任务,你只需从运算方法中返回或抛出非检查异常,或者调用completeExceptionally(Throwable)。

Specified by:

cancel in interface Future<V>

Parameters:

mayInterruptIfRunning - this value has no effect in the default implementation because interrupts are not used to control cancellation.

此值在默认实现中没有影响,因为中断不用于控制取消。

Returns:

true if this task is now cancelled 如果此任务当前已取消,返回true

isDone

public final boolean isDone()

Description copied from interface: Future

Returns true if this task completed. Completion may be due to normal termination, an exception, or cancellation -- in all of these cases, this method will return true.

如果任务已结束,返回true。结束可能是由于正常终止,异常或取消-在所有这些情况下,此方法将返回true。

Specified by:

isDone in interface Future<V>

Returns:

true if this task completed 如果此任务已结束,返回true。

isCancelled

public final boolean isCancelled()

Description copied from interface: Future

Returns true if this task was cancelled before it completed normally.

如果此任务在正常完成前被取消,返回true。

Specified by:

isCancelled in interface Future<V>

Returns:

true if this task was cancelled before it completed

如果此任务在完成前被取消,返回true。

isCompletedAbnormally

public final boolean isCompletedAbnormally()

Returns true if this task threw an exception or was cancelled.

如果此任务抛出异常或已取消,返回true。

Returns:

true if this task threw an exception or was cancelled

如果此任务抛出异常或已取消,返回true。

isCompletedNormally

public final boolean isCompletedNormally()

Returns true if this task completed without throwing an exception and was not cancelled.

如果此任务已经完成且没有抛异常和被取消,返回true。

Returns:

true if this task completed without throwing an exception and was not cancelled

如果此任务已经完成且没有抛异常和被取消,返回true。

getException

public final Throwable getException()

Returns the exception thrown by the base computation, or a CancellationException if cancelled, or null if none or if the method has not yet completed.

返回由基础计算引发的异常,如果已取消返回Cancellationexception,如果返回null则表示没有异常或方法尚未执行完成。

Returns:

the exception, or null if none

返回异常,如果没有异常返回null。

completeExceptionally

public void completeExceptionally(Throwable ex)

Completes this task abnormally, and if not already aborted or cancelled, causes it to throw the given exception upon join and related operations. This method may be used to induce exceptions in asynchronous tasks, or to force completion of tasks that would not otherwise complete. Its use in other situations is discouraged. This method is overridable, but overridden versions must invoke super implementation to maintain guarantees.

以非正常方式结束此任务,如果任务未中止或取消,则使其在join和相关操作时抛出给定异常。此方法可用于异步任务中引发异常,或强制完成其他不完成的任务,但其它情况下不建议使用此方法。此方法可被重写,但重写的版本必须调用父类实现来维持特有属性。

Parameters:

ex - the exception to throw. If this exception is not a RuntimeException or Error, the actual exception thrown will be a RuntimeException with cause ex.

抛出异常。如非RuntimeException或error,真正抛出的异常将被转换成RuntimeException。

complete

public void complete(V value)

Completes this task, and if not already aborted or cancelled, returning the given value as the result of subsequent invocations of join and related operations. This method may be used to provide results for asynchronous tasks, or to provide alternative handling for tasks that would not otherwise complete normally. Its use in other situations is discouraged. This method is overridable, but overridden versions must invoke super implementation to maintain guarantees.

完成此任务,如果任务未中止或取消,将给定值作为结果传递给后续调用join及相关操作。此方法可用于提供异步任务的结果,或为其他无法正常完成的任务提供替代处理,但其它情况下不建议使用此方法。此方法可被重写,但重写的版本必须调用父类实现来维持特有属性。

Parameters:

value - the result value for this task 此任务的结果值

quietlyComplete

public final void quietlyComplete()

Completes this task normally without setting a value. The most recent value established by setRawResult(V) (or null by default) will be returned as the result of subsequent invocations of join and related operations.

结束任务但不设定值。通过setRawResult(V)设定的最新值(或默认null)将传递给后续调用join及相关操作

Since:1.8

get

public final V get() throws InterruptedException, ExecutionException

Waits if necessary for the computation to complete, and then retrieves its result.

等待必要的计算完成,然后检索其结果。

Specified by:

get in interface Future<V>

Returns:

the computed result

Throws:

CancellationException - if the computation was cancelled

如果此运算被取消,抛出CancellationException

ExecutionException - if the computation threw an exception

如果此运算抛出异常,抛出ExecutionException

InterruptedException - if the current thread is not a member of a ForkJoinPool and was interrupted while waiting

如果当前线程非ForkJoinPool的成员或当前线程等待时被中断,抛出InterruptedException

get

public final V get(long timeout, TimeUnit unit)

throws InterruptedException,ExecutionException, TimeoutException

Waits if necessary for at most the given time for the computation to complete, and then retrieves its result, if available.

给定时间内等待必要的计算完成,如果结果可用则获取结果。

Specified by:

get in interface Future<V>

Parameters:

timeout - the maximum time to wait

unit - the time unit of the timeout argument

Returns:

the computed result

Throws:

CancellationException - if the computation was cancelled

如果此运算被取消,抛出CancellationException

ExecutionException - if the computation threw an exception

如果此运算抛出异常,抛出ExecutionException

InterruptedException - if the current thread is not a member of a ForkJoinPool and was interrupted while waiting

如果当前线程非ForkJoinPool的成员或当前线程等待时被中断,抛出InterruptedException

TimeoutException - if the wait timed out

如果超时未返回,抛出TimeoutException

quietlyJoin

public final void quietlyJoin()

Joins this task, without returning its result or throwing its exception. This method may be useful when processing collections of tasks when some have been cancelled or otherwise known to have aborted.

以静默方式执行此任务的join操作,但不返回其结果或抛出异常。此方法或许对下面这种情况是有用的:当处理容器内的任务时,一些任务被取消或因其它未知情形被终止。

quietlyInvoke

public final void quietlyInvoke()

Commences performing this task and awaits its completion if necessary, without returning its result or throwing its exception.

以静默方式开始执行此任务并等待任务结束,但不返回其结果或抛出异常。

helpQuiesce

public static void helpQuiesce()

Possibly executes tasks until the pool hosting the current task is quiescent. This method may be of use in designs in which many tasks are forked, but none are explicitly joined, instead executing them until all are processed.

可能直到池托管的当前任务不活动时才再开始执行任务。此方法或许对此情形是有用的:很多任务已经fork,但还未明确执行join操作,需要执行它们直到所有处理完毕。

reinitialize

public void reinitialize()

Resets the internal bookkeeping state of this task, allowing a subsequent fork. This method allows repeated reuse of this task, but only if reuse occurs when this task has either never been forked, or has been forked, then completed and all outstanding joins of this task have also completed. Effects under any other usage conditions are not guaranteed. This method may be useful when executing pre-constructed trees of subtasks in loops.

Upon completion of this method, isDone() reports false, and getException() reports null. However, the value returned by getRawResult is unaffected. To clear this value, you can invoke setRawResult(null).

重置此任务内部簿记状态以允许后续fork操作。这种方法允许反复重用此任务,但重用时,必须确保此任务从未被fork,或是已经被fork,而且这项任务所有未完成的join也已结束,在任何其他使用条件下的效果则不能保证。此方法或许对此情形是有用的:循环执行预构建的子任务树。

此方法完成后,isdone()报告false,getexception()报告null,但getRawResult的返回值不受影响。您可以调用setrawresult(null)来清除此值。

getPool

public static ForkJoinPool getPool()

Returns the pool hosting the current task execution, or null if this task is executing outside of any ForkJoinPool.

返回此任务的执行线程池,如果此任务在非ForkJoinPool中执行则返回null。

Returns:

the pool, or null if none

See Also:

inForkJoinPool()

inForkJoinPool

public static boolean inForkJoinPool()

Returns true if the current thread is a ForkJoinWorkerThread executing as a ForkJoinPool computation.

当前线程是ForkJoinWorkerThread,且以ForkJoinPool运算的方式执行,则返回true。

Returns:

true if the current thread is a ForkJoinWorkerThread executing as a ForkJoinPool computation, or false otherwise

当前线程是ForkJoinWorkerThread,且以ForkJoinPool运算的方式执行,则返回true。否则返回false。

tryUnfork

public boolean tryUnfork()

Tries to unschedule this task for execution. This method will typically (but is not guaranteed to) succeed if this task is the most recently forked task by the current thread, and has not commenced executing in another thread. This method may be useful when arranging alternative local processing of tasks that could have been, but were not, stolen.

试图取消此任务的执行计划。如果此任务是由当前线程最近fork的任务,且没有在另一个线程开始执行,此方法通常会成功(但不保证)。此方法对以下情形是可能有用的:当安排还没有被窃取的任务来替代本地处理的任务。

Returns:

true if unforked 如果取消fork成功返回true

getQueuedTaskCount

public static int getQueuedTaskCount()

Returns an estimate of the number of tasks that have been forked by the current worker thread but not yet executed. This value may be useful for heuristic decisions about whether to fork other tasks.

返回当前线程中已经fork的任务数的估计值(但不包括已执行的任务)。此值或许对关于尝试决定选择哪个线程去fork其它任务是有用的。

Returns:

the number of tasks 任务数

getSurplusQueuedTaskCount

public static int getSurplusQueuedTaskCount()

Returns an estimate of how many more locally queued tasks are held by the current worker thread than there are other worker threads that might steal them, or zero if this thread is not operating in a ForkJoinPool. This value may be useful for heuristic decisions about whether to fork other tasks. In many usages of ForkJoinTasks, at steady state, each worker should aim to maintain a small constant surplus (for example, 3) of tasks, and to process computations locally if this threshold is exceeded.

返回当前工作线程的队列中正在排队的任务的估计值(其它工作线程可窃取的任务);如果当前线程并不是ForkJoinPool中的线程则返回0。此值或许对关于尝试决定选择哪个线程去fork其它任务是有用的。此值在ForkJoinTasks中有很多用途,每个工作线程在稳定状态下都会尝试维持一定常量的剩余任务数(例如3),如果超过阈值则处理本地任务。

Returns:

the surplus number of tasks, which may be negative 剩余任务数,可能是负值

getRawResult

public abstract V getRawResult()

Returns the result that would be returned by join(), even if this task completed abnormally, or null if this task is not known to have been completed. This method is designed to aid debugging, as well as to support extensions. Its use in any other context is discouraged.

join()方法返回的结果(无论此任务是否异常完成),如果无法确定此任务是否已完成则返回null。此方法被设计用于帮助调试和支持扩展,在任何其他上下文环境中使用是被阻止的。

Returns:

the result, or null if not completed 返回结果,如果未完成则返回null

setRawResult

protected abstract void setRawResult(V value)

Forces the given value to be returned as a result. This method is designed to support extensions, and should not in general be called otherwise.

强制以给定值作为结果返回。此方法被设计用于支持扩展,一般不应该以其它方式调用。

Parameters:

value - the value

exec

protected abstract boolean exec()

Immediately performs the base action of this task and returns true if, upon return from this method, this task is guaranteed to have completed normally. This method may return false otherwise, to indicate that this task is not necessarily complete (or is not known to be complete), for example in asynchronous actions that require explicit invocations of completion methods. This method may also throw an (unchecked) exception to indicate abnormal exit. This method is designed to support extensions, and should not in general be called otherwise.

立即执行此任务的基础操作,当此方法返回时如结果为true,则该任务一定已经正常完成。其它情况该方法返回false,表明此任务未完成(或未知是否已完成),如在异步操作时需要显式调用检查完成状态的方法。此方法还可能抛出(非检查)异常以指示异常退出。此方法被设计用于支持扩展,一般不应该以其它方式调用。

Returns:

true if this task is known to have completed normally

如果明确知道任务已经正常完成,返回true。

peekNextLocalTask

protected static ForkJoinTask<?> peekNextLocalTask()

Returns, but does not unschedule or execute, a task queued by the current thread but not yet executed, if one is immediately available. There is no guarantee that this task will actually be polled or executed next. Conversely, this method may return null even if a task exists but cannot be accessed without contention with other threads. This method is designed primarily to support extensions, and is unlikely to be useful otherwise.

如果存在位于当前线程的任务队列但还未执行过的可立即执行的任务,则将其返回,但不取消计划或执行。不保证此任务确定会被移出或下一个执行。相反,如果任务存在但无法访问,也没有与其他线程的争用,则此方法可能返回null。此方法主要用于支持扩展,并且未必是有用的。

Returns:

the next task, or null if none are available 下一个任务,如果无可用任务返回null

pollNextLocalTask

protected static ForkJoinTask<?> pollNextLocalTask()

Unschedules and returns, without executing, the next task queued by the current thread but not yet executed, if the current thread is operating in a ForkJoinPool. This method is designed primarily to support extensions, and is unlikely to be useful otherwise.

如果当前线程位于ForkJoinPool,取消执行计划并返回:并非正在执行的且位于当前线程的下一个任务队列中但还未被执行的任务。此方法主要用于支持扩展,并且未必是有用的。

Returns:

the next task, or null if none are available 下一个任务,如果无可用任务返回null

pollTask

protected static ForkJoinTask<?> pollTask()

If the current thread is operating in a ForkJoinPool, unschedules and returns, without executing, the next task queued by the current thread but not yet executed, if one is available, or if not available, a task that was forked by some other thread, if available. Availability may be transient, so a null result does not necessarily imply quiescence of the pool this task is operating in. This method is designed primarily to support extensions, and is unlikely to be useful otherwise.

如果当前线程位于ForkJoinPool,取消执行计划并返回:非正在执行的任务,位于当前线程的下一个任务队列中但还未被执行的可用任务。如果无可用任务,任务可能已经被其它线程执行fork操作。可用性是极其短暂的,所以返回null结果不一定意味着此任务所在的线程池处于静止状态。此方法主要用于支持扩展,并且未必是有用的。

Returns:

a task, or null if none are available 下一个任务,如果无可用任务返回null

getForkJoinTaskTag

public final short getForkJoinTaskTag()

Returns the tag for this task.

返回此任务的标签

Returns:

the tag for this task 返回此任务的标签

Since:1.8

setForkJoinTaskTag

public final short setForkJoinTaskTag(short tag)

Atomically sets the tag value for this task.

原子操作设定此任务的标签

Parameters:

tag - the tag value 标签值

Returns:

the previous value of the tag 此标签的旧值

Since:1.8

compareAndSetForkJoinTaskTag

public final boolean compareAndSetForkJoinTaskTag(short e, short tag)

Atomically conditionally sets the tag value for this task. Among other applications, tags can be used as visit markers in tasks operating on graphs, as in methods that check: if (task.compareAndSetForkJoinTaskTag((short)0, (short)1)) before processing, otherwise exiting because the node has already been visited.

使用原子操作设定任务标签值。在其它应用中,标签可以用作在图中操作的任务的访问标记,如可在处理前判断if (task.compareAndSetForkJoinTaskTag((short)0, (short)1)), 如不为true则退出,因为此节点已经被访问。

Parameters:

e - the expected tag value 期望的标签值

tag - the new tag value 新的标签值

Returns:

true if successful; i.e., the current value was equal to e and is now tag.

操作成功返回true,如果当前值与期望值相同且是当前的标签值。

Since:1.8

adapt

public static ForkJoinTask<?> adapt(Runnable runnable)

Returns a new ForkJoinTask that performs the run method of the given Runnable as its action, and returns a null result upon join().

返回一个新的ForkJoinTask。当其被运行时执行给定的Runnable对象的run方法,执行join()方法时返回null。

Parameters:

runnable - the runnable action runnable动作

Returns:the task 返回此任务

adapt

public static <T> ForkJoinTask<T> adapt(Runnable runnable, T result)

Returns a new ForkJoinTask that performs the run method of the given Runnable as its action, and returns the given result upon join().

返回一个新的ForkJoinTask。当其被运行时执行给定的Runnable对象的run方法,执行join()方法时返回预给定结果。

Type Parameters:

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

Parameters:

runnable - the runnable action runnable动作

result - the result upon completion 完成时的返回结果

Returns:the task 返回此任务

adapt

public static <T> ForkJoinTask<T> adapt(Callable<? extends T> callable)

Returns a new ForkJoinTask that performs the call method of the given Callable as its action, and returns its result upon join(), translating any checked exceptions encountered into RuntimeException.

返回一个新的ForkJoinTask。当其被运行时执行给定的Callable 对象的call方法,执行join()方法时返回运行结果,期间遇到的任何检查型异常都将转换为RuntimeException。

Type Parameters:

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

Parameters:

callable - the callable action callable动作

Returns:

the task 返回此任务
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  fork/join Java JUC 并发