s2sh的项目框架,一次批量插入文件的数量最少上1万个以上,每个文件不超过1M,使用 页面超时 和 程序 不超时?求解决方法!
------解决思路----------------------
可以用ExecutorService 这个类,下面是一个用线程池时候下计算文件夹大小的例子,可以参考下
package cq.price;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class ConcurrentTotalFileSize {
public static void main(String[] args) throws InterruptedException,
ExecutionException, TimeoutException {
long start = System.nanoTime();
System.out.println("Total Size: "
+ new ConcurrentTotalFileSize()
.getTotalFileSizeOfFilesInDir(new File("F:\\资料")));
System.out.println("Time: " + (System.nanoTime() - start)
/ 1.0e9);
}
public long getTotalFileSizeOfFilesInDir(final File file)
throws InterruptedException, ExecutionException, TimeoutException {
if (file.isFile()) {
return file.length();
}
ExecutorService service = Executors.newFixedThreadPool(4);
long total;
try {
total = 0;
List<File> directories = new ArrayList<File>();
directories.add(file);
while (!directories.isEmpty()) {
final List<Future<SubDirectoriesAndSize>> partialResults = new ArrayList<Future<SubDirectoriesAndSize>>();
for (final File direcotry : directories) {
partialResults.add(service
.submit(new Callable<SubDirectoriesAndSize>() {
@Override
public SubDirectoriesAndSize call()
throws Exception {
return getTotalAndSubDirectories(direcotry);
}
}));
}
directories.clear();
for (Future<SubDirectoriesAndSize> future : partialResults) {
SubDirectoriesAndSize directoriesAndSize = future.get(100,
TimeUnit.SECONDS);
if (directoriesAndSize == null) {
continue;
}
total += directoriesAndSize.size;
directories.addAll(directoriesAndSize.subDirectories);
}
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage(), e);
} finally {
service.shutdown();
}
return total;
}
public SubDirectoriesAndSize getTotalAndSubDirectories(final File file) {
long total = 0;
List<File> subDirectories = new ArrayList<File>();
if (file.isDirectory()) {
File[] children = file.listFiles();
if (children != null) {
for (File child : children) {
if (child.isFile()) {
total += child.length();
} else {
subDirectories.add(child);
}
}
}
}
return new SubDirectoriesAndSize(total, subDirectories);
}
}
/**
* 记录当初文件夹的下文件的大小以及子文件夹
*
* @author Administrator
*
*/
class SubDirectoriesAndSize {
final public long size;
final public List<File> subDirectories;
public SubDirectoriesAndSize(long size, List<File> subDirectories) {
super();
this.size = size;
this.subDirectories = subDirectories;
};
}