ForkJoin翻譯

ForkJoinTask

翻譯

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.

這是一個在ForkJoinPool中運行的所有任務(wù)的抽象基類描滔,一個ForkJoinTask是一個類似線程,但是比真實線程更加輕量級的實體踪古。巨量的任務(wù)可能僅僅只需要ForkJoinPool中的幾個線程來運行即可含长,代價是一些使用上面的限制。

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.

主要的ForkJoinTask一旦明確的提交給ForkJoinPool之后會立馬執(zhí)行灾炭,同時你也可以同時手動調(diào)用ForkJoinPool.commonPool()中的相關(guān)方法茎芋,例如forkinvoke等蜈出。一旦開始田弥,其他子任務(wù)會按順訊執(zhí)行。正如類的名字一樣铡原,許多程序使用ForkJoinTask的時候僅僅用到了他的forkjoin方法偷厦,或者其衍生出來的invokeAll方法。然而燕刻,這個類還提供一系列的其他可以執(zhí)行一些高級事務(wù)的方法只泼,例如允許執(zhí)行其他fork/join任務(wù)的擴展機制等。

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卵洗。其高效的特性來源于一些列的限制(一些僅僅部分靜態(tài)強制的)请唱,這些現(xiàn)實反應(yīng)了ForkJoinTask的主要用途,就是一些在相互隔離的對象上面的純粹的的計算的操作过蹂。主要的協(xié)調(diào)機制是負(fù)責(zé)協(xié)調(diào)異步執(zhí)行的fork操作和在所有異步任務(wù)執(zhí)行完成之后的join操作十绑。計算任務(wù)應(yīng)該盡量獨立,避免同步方法或者同步塊酷勺,同時盡量最小化一些同步操作本橙,除了在join階段或者使用例如Phasers這種推薦的用來協(xié)調(diào)fork/join任務(wù)的同步方法〈嗨撸可分割的子任務(wù)不應(yīng)該執(zhí)行阻塞性的IO操作甚亭,且應(yīng)該盡量使用與其他任務(wù)獨立的變量。由于不允許一些例如IOExceptions這列異常的拋出击胜,這些規(guī)則可以不用強制的執(zhí)行亏狰。然而,計算過程中仍然會碰到一些未檢查的異常潜的,這些異常會拋出給那些執(zhí)行join操作的調(diào)用者骚揍。這些異常可能額外的包括來源于內(nèi)部資源耗盡的RejectedExecutionException啰挪,例如申請任務(wù)隊列內(nèi)存失敗信不。重拋出異常的行為與常規(guī)異常一致,但如果可能亡呵,包含啟動計算的線程及實際發(fā)生異常的線程的堆棧跟蹤信息(如顯式使用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. 如果一個任務(wù)以來與外部的同步操作或者IO操作下硕,那個其他任務(wù)應(yīng)該盡量少的依賴這個任務(wù)
  2. 為了盡量較少資源的影響,任務(wù)應(yīng)該盡量小汁胆,最好只執(zhí)行阻塞的動作
  3. 除非在使用了ForkJoinPool.ManagedBlocker里面的API梭姓,或者可能阻塞的任務(wù)比ForkJoinPool.getParallelism的值小,否則pool無法保證有足夠的線程保證有些的性能表現(xiàn)嫩码。

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是等待計算結(jié)束和獲取任務(wù)計算機過的主要方法誉尖,但是還有幾個變種方法可以使用:Future.get方法支持一些可打斷的或者定時的計算等待時間,并且可以通過Future的其他方法來獲取結(jié)果铸题。invoke方法在語法上面等于fork铡恕;join方法一直會嘗試在當(dāng)前線程上面執(zhí)行計算操作。上述的方法有何靜默的方式丢间,這個方式不會獲取結(jié)果探熔,亦不會上報異常。當(dāng)你想在所有任務(wù)結(jié)束之后處理結(jié)果和異常的情況下烘挫,這種方法會比較有用诀艰。invokeAll方法(在最近的幾個版本可以獲取使用)是一種最常見的執(zhí)行并行調(diào)用的形式:分發(fā)一系列的任務(wù)然后獲取他們的計算結(jié)果。

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表象的像是一個并行遞歸方法里面的調(diào)用(fork)和返回(join)其垄。在循環(huán)調(diào)用的場景下,返回(join)的調(diào)用順序應(yīng)該相反喜滨。例如捉捅,我們調(diào)用a.fork(); b.fork(); b.join(); a.join();,這個順序一般會比先執(zhí)行a.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 java.util.concurrent.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 java.util.concurrent.CancellationException.

我們可能需要在幾個層面來查詢?nèi)蝿?wù)的執(zhí)行狀態(tài):

  1. isDone為真棒口,如果一個任務(wù)完成(包括任務(wù)取消的情況下)
  2. isCompletedNormally 為真,如果一個任務(wù)沒有被取消且沒有碰到任何異常
  3. isCancelled為真辜膝,如果任務(wù)被取消(這種情況下getException活返回一個java.util.concurrent.CancellationException的異常)
  4. isCompletedAbnormally為真无牵,如果任務(wù)取消或者執(zhí)行途中碰到了異常,這種場景下getException將返回碰到的異吵Ф叮或者java.util.concurrent.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這個類一般不會直接去實現(xiàn)它茎毁。一般我們實現(xiàn)如下兩個抽象類,當(dāng)我們不需要返回任何計算結(jié)果的時候,實現(xiàn)RecursiveAction類七蜘,需要返回計算結(jié)果的時候谭溉,實現(xiàn)RecursiveTask,當(dāng)任務(wù)結(jié)束的時候需要調(diào)用其他動作的時候橡卤,我們使用CountedCompleter扮念。一般情況下,一個具體的ForkJoinTask的子類聲明自己的參數(shù)和構(gòu)造函數(shù)碧库,然后定義一個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) 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 or compareAndSetForkJoinTaskTag 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方法和它的變種方法當(dāng)且僅當(dāng)任務(wù)里面的計算不存在循環(huán)依賴的情況下適用嵌灰,即弄匕,該并行計算能夠被描述為一個有向無環(huán)圖(DAG)。否則沽瞭,由于循環(huán)依賴迁匠,計算任務(wù)會出現(xiàn)一個死鎖的情況。然而秕脓,在為一些不能直接構(gòu)建成有向無環(huán)圖的問題的子類的情況下柒瓣,這個框架支持其他的方法和技術(shù)(例如使用Phaser,helpQuiescecomplete)來解決這個問題。為了支持這種使用場景吠架,一個ForkJoinTask可以通過一個setForkJoinTaskTag或者compareAndSetForkJoinTaskTag來自動設(shè)置一個標(biāo)志位芙贫,通過getForkJoinTaskTag方法來檢查這個值。ForkJoinTask的實現(xiàn)傍药,不會使用這些受保護的方法和標(biāo)記磺平,但是他們在某些特定的子類的構(gòu)造中會有用。例如拐辽,并行圖的遍歷可以使用提供的方法來避免重復(fù)遍歷節(jié)點拣挪。(使用方法名來打標(biāo)記比較笨重,在這里我們鼓勵定義良好的方法名來明確表達它的用途)

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

為了防止被某些和其他輕量級的任務(wù)執(zhí)行框架綁定的實現(xiàn)覆蓋俱诸,大部分的基本方法是final類型的菠劝。創(chuàng)建新的fork/join操作類型的開發(fā)者們,應(yīng)該盡量少的實現(xiàn)一些protected方法睁搭,exec赶诊,setRawResultgetRawResult,同時可能會引入一個抽象計算方法园骆,這個方法可以在子類實現(xiàn)舔痪,同時可能依賴其他的該類提供的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應(yīng)該執(zhí)行小數(shù)據(jù)量的計算锌唾。大的任務(wù)應(yīng)該分解成小的子任務(wù)锄码,通常使用地柜的分解來實現(xiàn)。一個非常粗略的經(jīng)驗法則,一個任務(wù)應(yīng)該執(zhí)行超過100次滋捶,但是不超過10000此的基本計算步驟痛悯,并且應(yīng)該避免無限循環(huán)。如果任務(wù)太大炬太,并行性不能提高吞吐量灸蟆,如果太小驯耻,內(nèi)存和內(nèi)部任務(wù)的維護成本會過高亲族。

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.

這個類給RunnableCallable提供適配的方法,當(dāng)我們混合使用ForkJoinTasks任務(wù)和其他類型任務(wù)的時候可缚。當(dāng)所有任務(wù)都是這種類型的時候霎迫,考慮使用一個異步模式的池來管理。

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.

ForkJoinTasks任務(wù)是可序列化的帘靡,這使得這些任務(wù)能夠在一些外部擴展知给,例如遠(yuǎn)程執(zhí)行框架中使用。在任務(wù)執(zhí)行之前或者之后描姚,而不是在執(zhí)行過程中涩赢,都可以序列化任務(wù)。序列化在任務(wù)執(zhí)行過程是不可靠的轩勘。

Since:1.7Author:Doug Lea

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末筒扒,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子绊寻,更是在濱河造成了極大的恐慌花墩,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,270評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件澄步,死亡現(xiàn)場離奇詭異冰蘑,居然都是意外死亡,警方通過查閱死者的電腦和手機村缸,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,489評論 3 395
  • 文/潘曉璐 我一進店門祠肥,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人梯皿,你說我怎么就攤上這事仇箱。” “怎么了索烹?”我有些...
    開封第一講書人閱讀 165,630評論 0 356
  • 文/不壞的土叔 我叫張陵工碾,是天一觀的道長。 經(jīng)常有香客問我百姓,道長渊额,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,906評論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮旬迹,結(jié)果婚禮上火惊,老公的妹妹穿的比我還像新娘。我一直安慰自己奔垦,他們只是感情好屹耐,可當(dāng)我...
    茶點故事閱讀 67,928評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著椿猎,像睡著了一般惶岭。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上犯眠,一...
    開封第一講書人閱讀 51,718評論 1 305
  • 那天按灶,我揣著相機與錄音,去河邊找鬼筐咧。 笑死鸯旁,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的量蕊。 我是一名探鬼主播铺罢,決...
    沈念sama閱讀 40,442評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼残炮!你這毒婦竟也來了韭赘?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,345評論 0 276
  • 序言:老撾萬榮一對情侶失蹤吉殃,失蹤者是張志新(化名)和其女友劉穎辞居,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體蛋勺,經(jīng)...
    沈念sama閱讀 45,802評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡瓦灶,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,984評論 3 337
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了抱完。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片贼陶。...
    茶點故事閱讀 40,117評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖巧娱,靈堂內(nèi)的尸體忽然破棺而出碉怔,到底是詐尸還是另有隱情,我是刑警寧澤禁添,帶...
    沈念sama閱讀 35,810評論 5 346
  • 正文 年R本政府宣布撮胧,位于F島的核電站,受9級特大地震影響老翘,放射性物質(zhì)發(fā)生泄漏芹啥。R本人自食惡果不足惜锻离,卻給世界環(huán)境...
    茶點故事閱讀 41,462評論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望墓怀。 院中可真熱鬧汽纠,春花似錦、人聲如沸傀履。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,011評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽钓账。三九已至碴犬,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間官扣,已是汗流浹背翅敌。 一陣腳步聲響...
    開封第一講書人閱讀 33,139評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留惕蹄,地道東北人。 一個月前我還...
    沈念sama閱讀 48,377評論 3 373
  • 正文 我出身青樓治专,卻偏偏與公主長得像卖陵,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子张峰,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,060評論 2 355

推薦閱讀更多精彩內(nèi)容