Tuesday, February 17, 2015

How will you increment each element of an Integer array, utilizing all the cores of processor ?


We can use ForkJoin Framework to divide this task recursively into multiple sub tasks and fork them using multiple cpu's available to the JVM. Java 7 provides us with RecursiveAction class that can be extended to utilize ForkJoinPool framework with a great ease.


Java Code for Incrementing each element of Integer Array by 1
package org.shunya.interview;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;

class IncrementTask extends RecursiveAction {
    private final int THRESHOLD = 100;
    final long[] array;
    final int lo, hi;

    IncrementTask(long[] array, int lo, int hi) {
        this.array = array;
        this.lo = lo;
        this.hi = hi;
    }

    protected void compute() {
        if (hi - lo < THRESHOLD) {
            for (int i = lo; i < hi; ++i)
                array[i]++;
        } else {
            int mid = (lo + hi) >>> 1;
            invokeAll(new IncrementTask(array, lo, mid), new IncrementTask(array, mid, hi));
        }
    }

    public static void main(String[] args) {
        long[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9};
        IncrementTask incrementTask = new IncrementTask(array, 0, 9);
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        forkJoinPool.invoke(incrementTask);
    }
}

No comments:

Post a Comment

Your comment will be published after review from moderator