Skip to content

Instantly share code, notes, and snippets.

@pavel-mukhanov
Created March 4, 2014 07:06
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pavel-mukhanov/9341630 to your computer and use it in GitHub Desktop.
Save pavel-mukhanov/9341630 to your computer and use it in GitHub Desktop.
Find maximum value in array with ForkJoinPool
import java.util.Random;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
public class ForkJoinMax {
private static Random random = new Random();
private static final int N = 15000000;
private static int[] array = new int[N];
private static int THRESHOLD = 100;
static class FindMaxTask extends RecursiveTask<Integer> {
private int start;
private int end;
public FindMaxTask(int start, int end) {
this.start = start;
this.end = end;
}
@Override
protected Integer compute() {
int length = end - start;
if (length < THRESHOLD) {
return computeDirectly();
}
int offset = length / 2;
FindMaxTask left = new FindMaxTask(start, start + offset);
left.fork();
FindMaxTask right = new FindMaxTask(start + offset, end);
return Math.max(right.compute(), left.join());
}
private Integer computeDirectly() {
int max = Integer.MIN_VALUE;
for (int i = start; i < end; i++) {
array[i] = random.nextInt();
if (max < array[i]) {
max = array[i];
}
}
return max;
}
}
public static void main(String[] args) {
int max = new ForkJoinPool().invoke(new FindMaxTask(0, N));
System.out.println("max = " + max);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment