我正在开发一个从不同URL检索文件的应用程序。
有一个TreeSet包含要下载的目标。这是循环处理的,每个项目都由ExecutorService调用。这是一些代码:
private void retrieveDataFiles() {
if (this.urlsToRetrieve.size() > 0) {
System.out.println("Target URLs to retrieve: " + this.urlsToRetrieve.size());
ExecutorService executorProcessUrls = Executors.newFixedThreadPool(this.urlsToRetrieve.size());//could use fixed pool based on size of urls to retrieve
for (Entry target : this.urlsToRetrieve.entrySet()) {
final String fileName = (String) target.getKey();
final String url = (String) target.getValue();
String localFile = localDirectory + File.separator + fileName;
System.out.println(localFile);
executorProcessUrls.submit(new WikiDumpRetriever(url, localFile));
dumpFiles.add(localFile);
//TODO: figure out why only 2 files download
}
executorProcessUrls.shutdown();
try {
executorProcessUrls.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException ex) {
System.out.println("retrieveDataFiles InterruptedException: " + ex.getMessage());
}
} else {
System.out.println("No target URL's were retrieved");
}
}
然后是WikiDumpRetriever:
private static class WikiDumpRetriever implements Runnable {
private String wikiUrl;
private String downloadTo;
public WikiDumpRetriever(String targetUrl, String localDirectory) {
this.downloadTo = localDirectory;
this.wikiUrl = targetUrl;
}
public void downloadFile() throws FileNotFoundException, IOException, URISyntaxException {
HTTPCommunicationGet httpGet = new HTTPCommunicationGet(wikiUrl, "");
httpGet.downloadFiles(downloadTo);
}
@Override
public void run() {
try {
downloadFile();
} catch (FileNotFoundException ex) {
System.out.println("WDR: FileNotFound " + ex.getMessage());
} catch (IOException ex) {
System.out.println("WDR: IOException " + ex.getMessage());
} catch (URISyntaxException ex) {
System.out.println("WDR: URISyntaxException " + ex.getMessage());
}
}
}
如您所见,这是一个内部类。 TreeSet包含:
核心价值
enwiki-latest-pages-articles.xml.bz2:http://dumps.wikimedia.org/enwiki/latest/enwiki-latest-pages-articles.xml.bz2
elwiki-latest-pages-articles.xml.bz2:http://dumps.wikimedia.org/enwiki/latest/elwiki-latest-pages-articles.xml.bz2
zhwiki-latest-pages-articles.xml.bz2:http://dumps.wikimedia.org/enwiki/latest/zhwiki-latest-pages-articles.xml.bz2
hewiki-latest-pages-articles.xml.bz2:http://dumps.wikimedia.org/enwiki/latest/hewiki-latest-pages-articles.xml.bz2
问题在于此过程将下载四个文件中的两个。我知道所有四个都可用,并且我知道可以下载它们。但是,它们中只有2个随时处理。
任何人都可以帮我了解一下-我想念的是什么或我弄错了什么?
谢谢
nathj07
最佳答案
多亏了ppeterka-从源头上讲这是一个限制。因此,为了克服这个问题,我将固定线程池的大小设置为2。这意味着同时只能下载2个文件。
答案是找到供应商施加的限制并设置线程池:
ExecutorService executorProcessUrls = Executors.newFixedThreadPool(2);
我想接受一个答案,但似乎无法通过评论来解决。抱歉,如果这样做是错误的方法。
感谢所有指示-“小组思考”确实为我解决了这个问题。