DulcetAirman icon

Java-Fork/Join: Non-Recursive Task

DulcetAirman | PRO | 12/31/14 08:09:00 AM UTC | 0 ⭐ | 1402 👁️ | Never ⏰ | []
Java |

2.09 KB

|

None

|

0 👍

/

0 👎

package com.example.foo;
 
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
 
/**
 * https://humanoidreadable.wordpress.com/2014/12/31/forkjoin-nonrecursive-task/
 * 
 * @author Claude Martin
 *
 */
public class SomeClass {
 
  private static class Task1 extends ForkJoinTask<Integer> {
    private static final long serialVersionUID = 4577085552193799470L;
 
    private final Integer input;
    private Integer result = null;
 
    public Task1(Integer input) {
      this.input = input;
    }
 
    @Override
    public Integer getRawResult() {
      return this.result;
    }
 
    @Override
    protected void setRawResult(Integer value) {
      this.result = value;
    }
 
    @Override
    protected boolean exec() {
      ForkJoinTask<Integer> a = new Task2(this.input).fork();
      ForkJoinTask<Integer> b = new Task2(this.input + 1).fork();
      setRawResult(a.join() + b.join());
      return true;
    }
  }
 
  private static class Task2 extends ForkJoinTask<Integer> {
    private static final long serialVersionUID = -7037328571331917872L;
    private final Integer input;
    private Integer result = null;
 
    public Task2(Integer input) {
      this.input = input;
    }
 
    @Override
    public Integer getRawResult() {
      return this.result;
    }
 
    @Override
    protected void setRawResult(Integer value) {
      this.result = value;
    }
 
    @Override
    protected boolean exec() {
      System.out.format("Task2(%d) started%n", this.input);
 
      // This is the actual work:
      setRawResult(this.input * this.input);
 
      // Just to show that they really run in parallel:
      try {
        Thread.sleep(5000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
 
      System.out.format("Task2(%d) finished%n", this.input);
      return true;
    }
  }
 
  public static void main(String[] args) {
 
    Integer result = ForkJoinPool.commonPool().invoke(new Task1(5));
    System.out.println(result);
 
    // 5*5 = 25
    // 6*6 = 36
    // 25+36= 61
 
  }
}

Comments