Lecture Videos
  1  import java.util.concurrent.*;
  2  
  3  public class ParallelMax {
  4    public static void main(String[] args) {
  5      // Create a list
  6      final int N = 9000000;
  7      int[] list = new int[N];
  8      for (int i = 0; i < list.length; i++)
  9        list[i] = i;
 10  
 11      long startTime = System.currentTimeMillis();
 12      System.out.println("\nThe maximal number is " + max(list));
 13      long endTime = System.currentTimeMillis();
 14      System.out.println("Number of processors is " + 
 15        Runtime.getRuntime().availableProcessors()); 
 16      System.out.println("Time with " + (endTime - startTime) 
 17        + " milliseconds"); 
 18    }
 19    
 20    public static int max(int[] list) {
 21      RecursiveTask<Integer> task = new MaxTask(list, 0, list.length);
 22      ForkJoinPool pool = new ForkJoinPool();
 23      return pool.invoke(task);
 24    }
 25   
 26    private static class MaxTask extends RecursiveTask<Integer> {
 27      private final static int THRESHOLD = 1000;
 28      private int[] list;
 29      private int low;
 30      private int high;
 31  
 32      public MaxTask(int[] list, int low, int high) {
 33        this.list = list;
 34        this.low = low;
 35        this.high = high;
 36      }
 37  
 38      @Override
 39      public Integer compute() {
 40        if (high - low < THRESHOLD) {
 41          int max = list[0];
 42          for (int i = low; i < high; i++)
 43            if (list[i] > max)
 44              max = list[i];
 45          return new Integer(max);
 46        } 
 47        else {
 48          int mid = (low + high) / 2;
 49          RecursiveTask<Integer> left = new MaxTask(list, low, mid);
 50          RecursiveTask<Integer> right = new MaxTask(list, mid, high);
 51  
 52          right.fork();
 53          left.fork(); 
 54          return new Integer(Math.max(left.join().intValue(), 
 55            right.join().intValue()));
 56        }
 57      }
 58    }
 59  }