public class FileSize {
private final static ForkJoinPool forkJoinPool = new ForkJoinPool();
private static class FileSizeFinder extends RecursiveTask { final File file;
public FileSizeFinder(final File theFile) { file = theFile;}
@Override public Long compute() { long size = 0;
if (file.isFile()) {
size = file.length();
} else {
final File[] children = file.listFiles();
if (children != null) {
List> tasks = new ArrayList>();
for(final File child : children) {
if (child.isFile()) {
size += child.length();
} else {
tasks.add(new FileSizeFinder(child));
}
}
for(final ForkJoinTask task : invokeAll(tasks)) {
size += task.join();}
}
}
return size; }
}
public static void main(final String[] args) {
final long start = System.nanoTime();
final long total = forkJoinPool.invoke(new FileSizeFinder(new File(args[0])));
final long end = System.nanoTime();
System.out.println("Total Size: " + total);
System.out.println("Time taken: " + (end - start)/1.0e9);
}
}
阅读(914) | 评论(0) | 转发(0) |