jagamot
jagamot

Reputation: 5454

Java 7: Fork/Join Example - Did I get this right?

I am getting my hands dirty with Java 7 concurrency and parallelism feature - Fork/Join Framework.

I am trying to display the list of all directories under a given path. Can some one tell me if I got this correct?

Here is my main class - JoinForkExample that kicks off the task

package com.skilledmonster.examples;

import java.io.File;
import java.util.List;
import java.util.concurrent.ForkJoinPool;

public class JoinForkExample {
    public static void main(String[] args) {
        ForkJoinPool forkJoinPool = new ForkJoinPool() ;
        List<File> directories = forkJoinPool.invoke(new DirectoryListingTask(new File("C:/xampp"))) ;
         for (int i = 0; i < directories.size(); i++) {
            File file = (File) directories.get(i);
            System.out.println(file.getAbsolutePath());
        }
    }
}

And here is my actual task

package com.skilledmonster.examples;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.RecursiveTask;

public class DirectoryListingTask extends RecursiveTask<List<File>> {

    private static final FileFilter filter = new DirectoryFilter();

    private File file ;

    public DirectoryListingTask(File file) {
        this.file = file;
    }

    @Override
    protected List<File> compute() {
       List<RecursiveTask<List<File>>> forks = new LinkedList<>(); 
       List files = new ArrayList();
        if (file.isDirectory()) {
            File[] filteredFiles = file.listFiles(filter);
            if (null != filteredFiles) {
                files.addAll(Arrays.asList(filteredFiles));
            }
            for (File childFile : file.listFiles()) {
                DirectoryListingTask task = new DirectoryListingTask(childFile);
                forks.add(task);
                task.fork();
            }

            for (RecursiveTask<List<File>> task : forks) {
                files.addAll(task.join());
            }
        }
        return files ;
    }
}

I am pretty much getting the intended result. But I am not quite sure if I got this right. And surprising I don't notice any time difference in execution even when I executed the same without using join/fork framework.

Any thoughts!

Upvotes: 1

Views: 3415

Answers (1)

James Gan
James Gan

Reputation: 7116

As this work is primarily IO-bound, it's not very helpful to use Fork/Join here. I would suggest to try some computation intensive task instead. Also, please note the Fork/Join operation has overhead. If you use it to compute Fibonacchi series, it won't deserve it. And I would expect that performance is slower than sequential version.

Upvotes: 3

Related Questions