The fork/join framework is an implementation of the ExecutorService interface that helps you take advantage of multiple processors. It is designed for work that can be broken into smaller pieces recursively. The goal is to use all the available processing power to enhance the performance of your application.

简单翻一下主题思想:fork/join框架是ExecutorService接口的一个实现,它的目的是解决线程的派生问题。这个框架的本质是将一个任务分解成多个子任务,每个子任务用单独的线程去处理。这里用到了递归的思想。

As with any ExecutorService implementation, the fork/join framework distributes tasks to worker threads in a thread pool. The fork/join framework is distinct because it uses a work-stealing algorithm. Worker threads that run out of things to do can steal tasks from other threads that are still busy.

The center of the fork/join framework is the ForkJoinPool class, an extension of the AbstractExecutorService class. ForkJoinPool implements the core work-stealing algorithm and can execute ForkJoinTask processes.

Basic Use

The first step for using the fork/join framework is to write code that performs a segment of the work. Your code should look similar to the following pseudocode:

  1. if (my portion of the work is small enough)
  2. do the work directly
  3. else
  4. split my work into two pieces
  5. invoke the two pieces and wait for the results

Wrap this code in a ForkJoinTask subclass, typically using one of its more specialized types, either RecursiveTask (which can return a result) or RecursiveAction.

After your ForkJoinTask subclass is ready, create the object that represents all the work to be done and pass it to the invoke() method of a ForkJoinPool instance.

Blurring for Clarity

To help you understand how the fork/join framework works, consider the following example. Suppose that you want to blur an image. The original source image is represented by an array of integers, where each integer contains the color values for a single pixel. The blurred destination image is also represented by an integer array with the same size as the source.

Performing the blur is accomplished by working through the source array one pixel at a time. Each pixel is averaged with its surrounding pixels (the red, green, and blue components are averaged), and the result is placed in the destination array. Since an image is a large array, this process can take a long time. You can take advantage of concurrent processing on multiprocessor systems by implementing the algorithm using the fork/join framework. Here is one possible implementation:

  1. public class ForkBlur extends RecursiveAction {
  2. private int[] mSource;
  3. private int mStart;
  4. private int mLength;
  5. private int[] mDestination;
  6.  
  7. // Processing window size; should be odd.
  8. private int mBlurWidth = 15;
  9.  
  10. public ForkBlur(int[] src, int start, int length, int[] dst) {
  11. mSource = src;
  12. mStart = start;
  13. mLength = length;
  14. mDestination = dst;
  15. }
  16.  
  17. protected void computeDirectly() {
  18. int sidePixels = (mBlurWidth - 1) / 2;
  19. for (int index = mStart; index < mStart + mLength; index++) {
  20. // Calculate average.
  21. float rt = 0, gt = 0, bt = 0;
  22. for (int mi = -sidePixels; mi <= sidePixels; mi++) {
  23. int mindex = Math.min(Math.max(mi + index, 0),
  24. mSource.length - 1);
  25. int pixel = mSource[mindex];
  26. rt += (float)((pixel & 0x00ff0000) >> 16)
  27. / mBlurWidth;
  28. gt += (float)((pixel & 0x0000ff00) >> 8)
  29. / mBlurWidth;
  30. bt += (float)((pixel & 0x000000ff) >> 0)
  31. / mBlurWidth;
  32. }
  33.  
  34. // Reassemble destination pixel.
  35. int dpixel = (0xff000000 ) |
  36. (((int)rt) << 16) |
  37. (((int)gt) << 8) |
  38. (((int)bt) << 0);
  39. mDestination[index] = dpixel;
  40. }
  41. }
  42.  
  43. ...

Now you implement the abstract compute() method, which either performs the blur directly or splits it into two smaller tasks. A simple array length threshold helps determine whether the work is performed or split.

  1. protected static int sThreshold = 100000;
  2.  
  3. protected void compute() {
  4. if (mLength < sThreshold) {
  5. computeDirectly();
  6. return;
  7. }
  8.  
  9. int split = mLength / 2;
  10.  
  11. invokeAll(new ForkBlur(mSource, mStart, split, mDestination),
  12. new ForkBlur(mSource, mStart + split, mLength - split,
  13. mDestination));
  14. }

If the previous methods are in a subclass of the RecursiveAction class, then setting up the task to run in a ForkJoinPool is straightforward, and involves the following steps:

  1. Create a task that represents all of the work to be done.

    1. // source image pixels are in src
    2. // destination image pixels are in dst
    3. ForkBlur fb = new ForkBlur(src, 0, src.length, dst);
  2. Create the ForkJoinPool that will run the task.

    1. ForkJoinPool pool = new ForkJoinPool();
  3. Run the task.

    1. pool.invoke(fb);

For the full source code, including some extra code that creates the destination image file, see the ForkBlur example.

Standard Implementations

Besides using the fork/join framework to implement custom algorithms for tasks to be performed concurrently on a multiprocessor system (such as the ForkBlur.java example in the previous section), there are some generally useful features in Java SE which are already implemented using the fork/join framework. One such implementation, introduced in Java SE 8, is used by the java.util.Arrays class for its parallelSort() methods. These methods are similar to sort(), but leverage concurrency via the fork/join framework. Parallel sorting of large arrays is faster than sequential sorting when run on multiprocessor systems. However, how exactly the fork/join framework is leveraged by these methods is outside the scope of the Java Tutorials. For this information, see the Java API documentation.

Another implementation of the fork/join framework is used by methods in the java.util.streams package, which is part of Project Lambda scheduled for the Java SE 8 release. For more information, see the Lambda Expressions section.

JDK7新特性之fork/join框架的更多相关文章

  1. Java并发——Fork/Join框架

    为了防止无良网站的爬虫抓取文章,特此标识,转载请注明文章出处.LaplaceDemon/ShiJiaqi. http://www.cnblogs.com/shijiaqi1066/p/4631466. ...

  2. Java并发——Fork/Join框架与ForkJoinPool

    为了防止无良网站的爬虫抓取文章,特此标识,转载请注明文章出处.LaplaceDemon/ShiJiaqi. http://www.cnblogs.com/shijiaqi1066/p/4631466. ...

  3. Java 7 Fork/Join 框架

    在 Java7引入的诸多新特性中,Fork/Join 框架无疑是重要的一项.JSR166旨在标准化一个实质上可扩展的框架,以将并行计算的通用工具类组织成一个类似java.util中Collection ...

  4. 《java.util.concurrent 包源码阅读》22 Fork/Join框架的初体验

    JDK7引入了Fork/Join框架,所谓Fork/Join框架,个人解释:Fork分解任务成独立的子任务,用多线程去执行这些子任务,Join合并子任务的结果.这样就能使用多线程的方式来执行一个任务. ...

  5. Fork/Join 框架-设计与实现(翻译自论文《A Java Fork/Join Framework》原作者 Doug Lea)

    作者简介 Dong Lea任职于纽约州立大学奥斯威戈分校(State University of New York at Oswego),他发布了第一个广泛使用的java collections框架实 ...

  6. 【转】Fork/Join框架测试

    Fork/Join框架介绍 下面使用该框架计算0-50000000000的和,并比较普通计算方法.Fork/Join框架.Java8新特性三种计算方式的计算时间: import java.time.D ...

  7. 013-多线程-基础-Fork/Join框架、parallelStream讲解

    一.概述 Fork/Join框架是Java7提供了的一个用于并行执行任务的框架, 是一个把大任务分割成若干个小任务,最终汇总每个小任务结果后得到大任务结果的框架. 它同ThreadPoolExecut ...

  8. ☕【Java技术指南】「并发编程专题」Fork/Join框架基本使用和原理探究(基础篇)

    前提概述 Java 7开始引入了一种新的Fork/Join线程池,它可以执行一种特殊的任务:把一个大任务拆成多个小任务并行执行. 我们举个例子:如果要计算一个超大数组的和,最简单的做法是用一个循环在一 ...

  9. JAVA中的Fork/Join框架

    看了下Java Tutorials中的fork/join章节,整理下. 什么是fork/join框架 fork/join框架是ExecutorService接口的一个实现,可以帮助开发人员充分利用多核 ...

随机推荐

  1. Linux 查看某个用户的进程

    Linux 查看某个用户的进程 To view only the processes owned by a specific user, use the following command: top ...

  2. 《WPF程序设计指南》读书笔记——第8章 依赖属性

    1.依赖属性的效果 一旦规定视觉树上一个对象的fontsize属性,那么属于他的节点之下的所有对象都会沿袭这个属性,然而如果某个子节点明确的设定了自己的fontsize,就不会沿袭父节点的fontsi ...

  3. 【分享】SQL Server优化50法

    虽然查询速度慢的原因很多,但是如果通过一定的优化,也可以使查询问题得到一定程度的解决. 查询速度慢的原因很多,常见如下几种: 没有索引或者没有用到索引(这是查询慢最常见的问题,是程序设计的缺陷) I/ ...

  4. 利用JQuery的$.ajax()可以很方便的调用asp.net的后台方法

    利用JQuery的$.ajax()可以很方便的调用asp.net的后台方法. 先来个简单的实例热热身吧. 1.无参数的方法调用 asp.net code: view plaincopy to clip ...

  5. Oracle创建序列

    CREATE SEQUENCE IF NOT EXISTS seq_fund_execute

  6. SC命令执行出现Access is denied

    在命令行中先是打开远程链接:net use \\computername(or ip)\ipc$ "password" /user:"[domain\]username& ...

  7. Xcode常用快捷键及代码格式刷(缩进)方法-b

    Xcode版本:4.5.1 一.总结的常用命令: 隐藏xcode command+h 退出xcode command+q 关闭窗口 command+w 关闭所有窗口 command+option+w ...

  8. 无锁算法CAS 概述

    无锁算法CAS 概述 JDK5.0以后的版本都引入了高级并发特性,大多数的特性在java.util.concurrent包中,是专门用于多线并发编程的,充分利用了现代多处理器和多核心系统的功能以编写大 ...

  9. 设计模式之:组合模式(Composite)

    支持原创:http://blog.csdn.net/hguisu/article/details/7530783 设计模式(七)组合模式Composite(结构型) 1. 概述 在数据结构里面,树结构 ...

  10. js中批量处理样式——cssText的使用

    http://www.cnblogs.com/snandy/archive/2011/03/12/1980444.html