Advertisement
DulcetAirman

Java-Fork/Join: Non-Recursive Task

Dec 31st, 2014
814
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.09 KB | None | 0 0
  1. package com.example.foo;
  2.  
  3. import java.util.concurrent.ForkJoinPool;
  4. import java.util.concurrent.ForkJoinTask;
  5.  
  6. /**
  7.  * https://humanoidreadable.wordpress.com/2014/12/31/forkjoin-nonrecursive-task/
  8.  *
  9.  * @author Claude Martin
  10.  *
  11.  */
  12. public class SomeClass {
  13.  
  14.   private static class Task1 extends ForkJoinTask<Integer> {
  15.     private static final long serialVersionUID = 4577085552193799470L;
  16.  
  17.     private final Integer input;
  18.     private Integer result = null;
  19.  
  20.     public Task1(Integer input) {
  21.       this.input = input;
  22.     }
  23.  
  24.     @Override
  25.     public Integer getRawResult() {
  26.       return this.result;
  27.     }
  28.  
  29.     @Override
  30.     protected void setRawResult(Integer value) {
  31.       this.result = value;
  32.     }
  33.  
  34.     @Override
  35.     protected boolean exec() {
  36.       ForkJoinTask<Integer> a = new Task2(this.input).fork();
  37.       ForkJoinTask<Integer> b = new Task2(this.input + 1).fork();
  38.       setRawResult(a.join() + b.join());
  39.       return true;
  40.     }
  41.   }
  42.  
  43.   private static class Task2 extends ForkJoinTask<Integer> {
  44.     private static final long serialVersionUID = -7037328571331917872L;
  45.     private final Integer input;
  46.     private Integer result = null;
  47.  
  48.     public Task2(Integer input) {
  49.       this.input = input;
  50.     }
  51.  
  52.     @Override
  53.     public Integer getRawResult() {
  54.       return this.result;
  55.     }
  56.  
  57.     @Override
  58.     protected void setRawResult(Integer value) {
  59.       this.result = value;
  60.     }
  61.  
  62.     @Override
  63.     protected boolean exec() {
  64.       System.out.format("Task2(%d) started%n", this.input);
  65.  
  66.       // This is the actual work:
  67.       setRawResult(this.input * this.input);
  68.  
  69.       // Just to show that they really run in parallel:
  70.       try {
  71.         Thread.sleep(5000);
  72.       } catch (InterruptedException e) {
  73.         e.printStackTrace();
  74.       }
  75.  
  76.       System.out.format("Task2(%d) finished%n", this.input);
  77.       return true;
  78.     }
  79.   }
  80.  
  81.   public static void main(String[] args) {
  82.  
  83.     Integer result = ForkJoinPool.commonPool().invoke(new Task1(5));
  84.     System.out.println(result);
  85.  
  86.     // 5*5 = 25
  87.     // 6*6 = 36
  88.     // 25+36= 61
  89.  
  90.   }
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement