Created
March 4, 2014 07:06
-
-
Save pavel-mukhanov/9341630 to your computer and use it in GitHub Desktop.
Find maximum value in array with ForkJoinPool
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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