Functional Java – Parallel Map

Functional Java is an open source library bringing functional programming concepts into the Java world. Features like up to 8-arity Functions, immutable collections with filters, function binding, folding are well described on the library’s site.

What lacks good examples is the fj.control.parallel package providing (among many other things) framework for applying operations to collections in parallel. It is simple to use and I think you can benefit from it in many scenarios e.g. transforming collection of objects when the operation depends on an external shared resource.

Let’s test it. I’ve prepared a function that reads form the file system and performs some calculations:

F f = new F() {
    public Integer f(Integer i) {
        int r = 0;
        for (int j = 1; j < 10; j++) {
            File f = new File("/tmp");
            for (String fileName : f.list()) {
                r = r + f.getName().length();
            }
        }
        return r;
    }
};

And several tests like the one below, that apply this function to the 1000 element arrays:

@Test
public void evaluateInTwoThreads() {
    ExecutorService executorService = Executors.newFixedThreadPool(2);
    Strategy s = Strategy.executorStrategy(executorService);
    long startTime = System.currentTimeMillis();
    List> p1 = s.parMap(f, List.range(1, 1000));
    long endTime = System.currentTimeMillis();
    System.out.println("Duration fixed pool 2: " + (endTime - startTime) + "ms.");
}

Results:

Duration sequential: 2271ms.
Duration fixed pool 2: 1361ms.
Duration fixed pool 4: 1677ms.
Duration fixed pool 10: 1203ms.

As you can see this is a simple way to benefit (in similar cases) from multicore processors. There will be no time improvement from adding more threads to perform the computation.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.