1

I have a thread pool to get through all of my files of a specific drive. The problem is that my process never ends.

Here is my code:

private static ExecutorService  service = Executors.newFixedThreadPool(250);
private static ArrayList<File>  files   = new ArrayList<>();
private static int              count   = 0;

public static void main(String[] args) throws InterruptedException {
    long before = currentTimeMillis();
    service.execute(() -> countFiles(new File("C://")));
    service.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);

    System.out.println((currentTimeMillis() - before) / 1000.0 + ", " + count);
}

public static void countFiles(File folder) {
    try {
        if (!folder.exists()) return;
        if (folder.getName().startsWith("$")) return;
        for (File file : folder.listFiles()) {
            if (file.isDirectory()) {
                service.execute(() -> countFiles(file));
            } else {
                files.add(file);
                count++;
            }
        }
    } catch (Exception e) {
        return;
    }
}

I tried putting service.shutdown(); before service.awaitTermination(...); but it blocks new executions.

How can I shutdown the service once all my files are stored in the ArrayList?

MrYannKee
  • 169
  • 1
  • 8
  • `count++` isn't thread-safe. You need to synchronize or use an `AtomicInteger`. `files` also needs to be synchronized or some concurrent alternative. – shmosel Mar 06 '17 at 20:34
  • It seems a bad implementation. The app create a runable for each Directory any levels? The app should create runable for top levels of sub-directories only. – LHA Mar 06 '17 at 20:35

0 Answers0