I am trying to process an image using a ForkJoinPool in java. I used streams to do some custom operations on the image. I am trying to use ForkJoinPool for getRGB
and setRGB
methods. How do I achieve parallelism on getRGB
methods?
@Override
public int[] getRGB(int xStart, int yStart, int w, int h, int[] rgbArray,int offset, int scansize) {
int[][] sol = new int[h][w];
int threshold = w;
class RecursiveSetter extends RecursiveAction {
int from;
int to;
FJBufferedImage image;
RecursiveSetter(int from, int to, FJBufferedImage image) {
this.from = from;
this.to = to;
this.image = image;
}
@Override
protected void compute() {
System.out.println("From : " + from + " To : " + to);
if (from >= to) return;
if (to - from == 1) {
computeDirectly(from);
return;
} else {
int mid = from + (to - from) / 2;
System.out.println("From : " + from + " To : " + to +
"Mid :" + mid);
invokeAll(
new RecursiveSetter(from, mid, image),
new RecursiveSetter(mid + 1, to, image));
return;
}
}
void computeDirectly(int row) {
sol[from] = image.getRealRGB(from, 0, w, 1, null, offset,
scansize);
}
}
ForkJoinPool pool = new ForkJoinPool(Runtime.getRuntime().availableProcessors());
pool.invoke(new RecursiveSetter(0, h-1, this));
return Arrays.stream(sol)
.flatMapToInt(Arrays::stream)
.toArray();
}
The getRealRGB
just proxies to the method of BufferedImage
. I understand this may be impractical but I just want to know how can I use ForkJoinPool in this context. And yeah, the above code is throwing ArrayIndexOutOfBound
Exception. Please give suggestion about how to split the work load (row vs col vs small grid. Right now, i am doing this split by row) and how to decide the threshold.