More code

Posted Thu, 22 Nov 2007 13:06:12 GMT

I’ve been exploring the java.util.concurrent package, and just thought I post some more code:

public class ParallelCounter {

    public int countWords1(List files) {
        ExecutorService executorService = Executors.newFixedThreadPool(4);
        List> counters = new ArrayList>();
        for(final File file : files) {
            counters.add(new Callable() {
                public Integer call() {
                    System.out.println("Starting file " + file.getName() + " at " + System.currentTimeMillis());
                    WordCounter counter = new WordCounter();
                    int count =  counter.count(file);
                    System.out.println("Done file " + file.getName() + " at " + System.currentTimeMillis());
                    return count;
                }
            });
        }
        try {
            List> results = executorService.invokeAll(counters);
            int totalCount = 0;
            for (Future future : results) {
                totalCount += future.get();
            }
            return totalCount;
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        ParallelCounter counter = new ParallelCounter();
        List files = new ArrayList(args.length);
        for (String filename : args) {
            files.add(new File(filename));
        }
        System.out.println("Total word count is " + counter.countWords1(files));
        System.out.println("Total elapsed time " +
(System.currentTimeMillis() - start));
    }
}

Comments

  1. Yuri Schimke said about 3 hours later:
    This is more suited to the CompletionService http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/CompletionService.html With the completion service, you don't have to worry about the order that the results execute in. Your current example, it doesn't really matter. But if the tasks can take variable amount of time, then you don't want to block on the first task, while you could be processing results of other finished tasks.

Trackbacks

Use the following link to trackback from your own site:
http://www.supplesoftware.com/articles/trackback/58

(leave url/email »)

  

Home

Who's George?

Recent entries