AwsGuy
AwsGuy

Reputation: 11

ExecutorService concurrency acts erratic and unstable

I have a project about concurrency and I have some trouble with the behaviour of my code. I am walking a file tree to find all files, and if I find a file which ends on .txt I submit a task to the executor. A thread will open the file and check what number in the file is the biggest. I then create an object, which holds the path for the file and the biggest number for that file. I append the object to a synchronized arraylist. But when I run the code, my arraylist sometimes have 1 object in it or 5 or 112 or 64. There should be 140 objects every time I run it. I hope you guys knows what the problem is.

public static List< Result > AllFiles( Path dir ) throws InterruptedException{

    final List<Result> resultlist = new ArrayList<Result>();
    final List<Result> synclist;
    synclist = Collections.synchronizedList(resultlist);

    ExecutorService exec 
        = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() + 1);
    try {
        Files.walk(dir).forEach(i -> {
            String pathfile = i.getFileName().toString();

            if (pathfile.contains(".txt")) {
                exec.submit(() -> {
                    int high = findHighest(i);
                    ResultObj obj = new ResultObj(i, high);
                    synclist.add(obj);       
                });
            }
        });
        exec.shutdown();
        try {
            exec.awaitTermination(1, TimeUnit.NANOSECONDS);
        } catch (InterruptedException ex) {}
    } catch (IOException ex) {} 

    System.out.println(synclist);
    System.out.println(synclist.size());
    return synclist;       
}

Upvotes: 1

Views: 65

Answers (1)

Warren Dew
Warren Dew

Reputation: 8928

You are only waiting 1 nanosecond in your awaitTermination call for your ExecutorService to shut down. As a result, you may be printing synclist before some of your files have been processed.

Upvotes: 1

Related Questions