ForkJoinPool

来源:互联网 发布:js中syntax error 编辑:程序博客网 时间:2024/06/07 11:37

ForkJoinPool 是 Java SE 7 新功能“分叉/结合框架”的核心类,现在可能乏人问津,但我觉得它迟早会成为主流。分叉/结合框架是一个比较特殊的线程池框架,专用于需要将一个任务不断分解成子任务(分叉),再不断进行汇总得到最终结果(结合)的计算过程。比起传统的线程池类ThreadPoolExecutorForkJoinPool 实现了工作窃取算法,使得空闲线程能够主动分担从别的线程分解出来的子任务,从而让所有的线程都尽可能处于饱满的工作状态,提高执行效率。

ForkJoinPool 提供了三类方法来调度子任务:

execute 系列

子任务由 ForkJoinTask 的实例来代表。它是一个抽象类,JDK 为我们提供了两个实现:RecursiveTask 和 RecursiveAction,分别用于需要和不需要返回计算结果的子任务。ForkJoinTask 提供了三个静态的 invokeAll 方法来调度子任务,注意只能在 ForkJoinPool 执行计算的过程中调用它们。

ForkJoinPool 和 ForkJoinTask 还提供了很多让人眼花缭乱的公共方法,其实它们大多数都是其内部实现去调用的,对于应用开发人员来说意义不大。

下面以统计 D 盘文件个数为例。这实际上是对一个文件树的遍历,我们需要递归地统计每个目录下的文件数量,最后汇总,非常适合用分叉/结合框架来处理:

 

 

Java代码  收藏代码
  1. // 处理单个目录的任务  
  2. public class CountingTask extends RecursiveTask<Integer> {  
  3.     private Path dir;  
  4.    
  5.     public CountingTask(Path dir) {  
  6.         this.dir = dir;  
  7.     }  
  8.    
  9.     @Override  
  10.     protected Integer compute() {  
  11.         int count = 0;  
  12.         List<CountingTask> subTasks = new ArrayList<>();  
  13.    
  14.         // 读取目录 dir 的子路径。  
  15.         try (DirectoryStream<Path> ds = Files.newDirectoryStream(dir)) {  
  16.             for (Path subPath : ds) {  
  17.                 if (Files.isDirectory(subPath, LinkOption.NOFOLLOW_LINKS)) {  
  18.                     // 对每个子目录都新建一个子任务。  
  19.                     subTasks.add(new CountingTask(subPath));  
  20.                 } else {  
  21.                     // 遇到文件,则计数器增加 1。  
  22.                     count++;  
  23.                 }  
  24.             }  
  25.    
  26.             if (!subTasks.isEmpty()) {  
  27.                 // 在当前的 ForkJoinPool 上调度所有的子任务。  
  28.                 for (CountingTask subTask : invokeAll(subTasks)) {  
  29.                     count += subTask.join();  
  30.                 }  
  31.             }  
  32.         } catch (IOException ex) {  
  33.             return 0;  
  34.         }  
  35.         return count;  
  36.     }  
  37. }  
  38.    
  39. // 用一个 ForkJoinPool 实例调度“总任务”,然后敬请期待结果……  
  40. Integer count = new ForkJoinPool().invoke(new CountingTask(Paths.get("D:/")));  

 

 

 

在我的笔记本上,经多次运行这段代码,耗费的时间稳定在 600 豪秒左右。普通线程池(Executors.newCachedThreadPool())耗时 1100 毫秒左右,足见工作窃取的优势。

结束本文前,我们来围观一个最神奇的结果:单线程算法(使用 Files.walkFileTree(...))比这两个都快,平均耗时 550 毫秒!这警告我们并非引入多线程就能优化性能,并须要先经过多次测试才能下结论。

 

 

转自:http://www.blogjava.net/shinzey/  

 

 

 

 

实际测试

 

Java代码  收藏代码
  1. package com.forkjoin.countdir;  
  2.   
  3. import java.io.File;  
  4. import java.util.ArrayList;  
  5. import java.util.List;  
  6. import java.util.concurrent.ForkJoinPool;  
  7. import java.util.concurrent.RecursiveTask;  
  8.   
  9. import com.util.DateTime;  
  10.   
  11. public class CountTaskRecursive extends RecursiveTask {  
  12.   
  13.     int sum =0;  
  14.     File file ;  
  15.       
  16.     public CountTaskRecursive(File file) {  
  17.         this.file = file;  
  18.     }  
  19.       
  20.     @Override  
  21.     protected Integer compute() {  
  22.         Integer csum =0;  
  23.         List<CountTaskRecursive> tasklist = new ArrayList<CountTaskRecursive>() ;  
  24.         if(file.isDirectory())  
  25.         {  
  26.             for(File f:file.listFiles())  
  27.             {  
  28.                 CountTaskRecursive t = new CountTaskRecursive(f);  
  29.                 tasklist.add(t);  
  30.             }  
  31.         }  
  32.         else  
  33.             csum ++;  
  34.         if(!tasklist.isEmpty())  
  35.         {  
  36.             for(CountTaskRecursive t :invokeAll(tasklist))  
  37.                 csum += (Integer)t.join();  
  38.         }  
  39.         return csum;  
  40.     }  
  41.   
  42.     public static void main(String[] args) {  
  43.         DateTime dt = new DateTime() ;  
  44.         System.out.println("系统日期:"+dt.getDate()) ;  
  45.         System.out.println("中文日期:"+dt.getDateComplete()) ;  
  46.         System.out.println("时间戳:"+dt.getTimeStamp()) ;  
  47.         CountTaskRecursive task = new CountTaskRecursive(new File("F:\\私人资料"));  
  48.         Integer sum = (Integer)new ForkJoinPool().invoke(task);  
  49.         System.out.println(sum);  
  50.         dt = new DateTime() ;  
  51.         System.out.println("系统日期:"+dt.getDate()) ;  
  52.         System.out.println("中文日期:"+dt.getDateComplete()) ;  
  53.         System.out.println("时间戳:"+dt.getTimeStamp()) ;  
  54.     }  
  55. }  

 

Java代码  收藏代码
  1. package com.forkjoin.countdir;  
  2. import java.io.File;  
  3. import java.security.Timestamp;  
  4. import java.util.Calendar;  
  5.   
  6. import com.util.DateTime;  
  7.   
  8.   
  9.   
  10. public class CountTaskSingle {  
  11.     static int sum = 0;  
  12.       
  13.     public void countDir(File file)  
  14.     {  
  15.         if(file.isDirectory())  
  16.         {  
  17.             for(File f:file.listFiles())  
  18.                 countDir(f);  
  19.         }  
  20.         else  
  21.             sum++;  
  22.           
  23.     }  
  24.       
  25.     public static void main(String[] args) {  
  26.         CountTaskSingle ins = new CountTaskSingle();  
  27.         DateTime dt = new DateTime() ;  
  28.         System.out.println("系统日期:"+dt.getDate()) ;  
  29.         System.out.println("中文日期:"+dt.getDateComplete()) ;  
  30.         System.out.println("时间戳:"+dt.getTimeStamp()) ;  
  31.         ins.countDir(new File("F:\\私人资料"));  
  32.         System.out.println(sum);  
  33.         dt = new DateTime() ;  
  34.         System.out.println("系统日期:"+dt.getDate()) ;  
  35.         System.out.println("中文日期:"+dt.getDateComplete()) ;  
  36.         System.out.println("时间戳:"+dt.getTimeStamp()) ;  
  37.     }  
  38. }  

 

 

Java代码  收藏代码
  1. package com.util;  
  2.   
  3. import java.util.*; // 导入需要的工具包  
  4. public class DateTime { // 以后直接通过此类就可以取得日期时间  
  5.     private Calendar calendar = null// 声明一个Calendar对象,取得时间  
  6.     public DateTime() { // 构造方法中直接实例化对象  
  7.         this.calendar = new GregorianCalendar();  
  8.     }  
  9.     public String getDate() { // 得到的是一个日期:格式为:yyyy-MM-dd HH:mm:ss.SSS  
  10.         // 考虑到程序要频繁修改字符串,所以使用StringBuffer提升性能  
  11.         StringBuffer buf = new StringBuffer();  
  12.         buf.append(calendar.get(Calendar.YEAR)).append("-"); // 增加年  
  13.         buf.append(this.addZero(calendar.get(Calendar.MONTH) + 12)).append("-"); // 增加月  
  14.         buf.append(this.addZero(calendar.get(Calendar.DAY_OF_MONTH), 2)).append(" "); // 取得日  
  15.         buf.append(this.addZero(calendar.get(Calendar.HOUR_OF_DAY), 2)).append(":"); // 取得时  
  16.         buf.append(this.addZero(calendar.get(Calendar.MINUTE), 2)).append(":");  
  17.         buf.append(this.addZero(calendar.get(Calendar.SECOND), 2)).append(".");  
  18.         buf.append(this.addZero(calendar.get(Calendar.MILLISECOND), 3));  
  19.         return buf.toString();  
  20.     }  
  21.     public String getDateComplete() { // 得到的是一个日期:格式为:yyyy年MM月dd日 HH时mm分ss秒SSS毫秒  
  22.         // 考虑到程序要频繁修改字符串,所以使用StringBuffer提升性能  
  23.         StringBuffer buf = new StringBuffer();  
  24.         buf.append(calendar.get(Calendar.YEAR)).append("年"); // 增加年  
  25.         buf.append(this.addZero(calendar.get(Calendar.MONTH) + 12)).append("月"); // 增加月  
  26.         buf.append(this.addZero(calendar.get(Calendar.DAY_OF_MONTH), 2)).append("日"); // 取得日  
  27.         buf.append(this.addZero(calendar.get(Calendar.HOUR_OF_DAY), 2)).append("时"); // 取得时  
  28.         buf.append(this.addZero(calendar.get(Calendar.MINUTE), 2)).append("分"); // 取得分  
  29.         buf.append(this.addZero(calendar.get(Calendar.SECOND), 2)).append("秒"); // 取得秒  
  30.         buf.append(this.addZero(calendar.get(Calendar.MILLISECOND), 3)).append("毫秒"); // 取得毫秒  
  31.         return buf.toString();  
  32.     }  
  33.     public String getTimeStamp() { // 得到的是一个时间戳  
  34.         // 考虑到程序要频繁修改字符串,所以使用StringBuffer提升性能  
  35.         StringBuffer buf = new StringBuffer();  
  36.         buf.append(calendar.get(Calendar.YEAR)); // 增加年  
  37.         buf.append(this.addZero(calendar.get(Calendar.MONTH) + 12)); // 增加月  
  38.         buf.append(this.addZero(calendar.get(Calendar.DAY_OF_MONTH), 2)); // 取得日  
  39.         buf.append(this.addZero(calendar.get(Calendar.HOUR_OF_DAY), 2)); // 取得时  
  40.         buf.append(this.addZero(calendar.get(Calendar.MINUTE), 2)); // 取得分  
  41.         buf.append(this.addZero(calendar.get(Calendar.SECOND), 2)); // 取得秒  
  42.         buf.append(this.addZero(calendar.get(Calendar.MILLISECOND), 3)); // 取得毫秒  
  43.         return buf.toString();  
  44.     }  
  45.     // 考虑到日期中存在前导0,所以在此处加上补零的方法  
  46.     private String addZero(int num, int len) {  
  47.         StringBuffer s = new StringBuffer();  
  48.         s.append(num);  
  49.         while (s.length() < len) { // 如果长度不足,则继续补0  
  50.             s.insert(0"0"); // 在第一个位置处补0  
  51.         }  
  52.         return s.toString();  
  53.     }  
  54. };  

 

 

执行结果:

单线程执行结果

 

系统日期:2012-05-09 23:59:07.468

中文日期:2012年05月09日23时59分07秒468毫秒

时间戳:20120509235907468

389578

系统日期:2012-05-09 23:59:56.421

中文日期:2012年05月09日23时59分56秒421毫秒

时间戳:20120509235956421

 

多线程执行结果

 

系统日期:2012-05-10 00:01:57.500

中文日期:2012年05月10日00时01分57秒500毫秒

时间戳:20120510000157500

389578

系统日期:2012-05-10 00:09:00.281

中文日期:2012年05月10日00时09分00秒281毫秒

时间戳:20120510000900281

 

异步执行指定的任务。
invoke 和 invokeAll
执行指定的任务,等待完成,返回结果。
submit 系列
异步执行指定的任务并立即返回一个 Future 对象。
原创粉丝点击