我正在开发一个可以从不同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-最新页面-文章.xml.bz2:http://dumps.wikimedia.org/enwiki/latest/enwiki-latest-pages-articles.xml.bz2
elwiki-最新页面-文章.xml.bz2:http://dumps.wikimedia.org/enwiki/latest/elwiki-latest-pages-articles.xml.bz2
日维基-最新页面-文章.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
问题是这个过程会下载四个文件中的两个。我知道所有四个都是可用的,而且我知道它们可以下载。然而,在任何时候,只有两个进程。
有没有人能为我解释一下--我遗漏了什么,或者我搞错了什么?
谢谢nathj07
发布于 2012-11-05 18:17:21
多亏了ppeterka --从源头上来说,这是一个限制。因此,为了克服这个问题,我将固定的线程池大小设置为2。这意味着同时只下载2个文件。
然后,答案是找到供应商强加的限制并设置线程池:
ExecutorService executorProcessUrls = Executors.newFixedThreadPool(2);我想接受一个答案,但似乎无法接受评论。如果这是错误的做法,我深表歉意。
感谢大家的指点--“群体思维”真的帮我解决了这个问题。
https://stackoverflow.com/questions/13157427
复制相似问题