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?