내가 전화를 병렬화하고 싶습니다,하지만 당신은 경계 BlockingQueue
와 함께 ExecutorService
을 사용한다 메모리
에 전체 파일을 읽어야하는 경우 잘 모르겠어요. 백만 라인을 읽으면 BlockingQueue
이 가득 찰 때까지 스레드 풀에 작업을 제출합니다. 이 방법을 사용하면 미리 파일의 모든 행을 읽지 않아도 HTTP 요청을 동시에 100 개 (또는 원하는 수만큼) 실행할 수 있습니다.
대기열이 가득 차면 차단하는 RejectedExecutionHandler
을 설정해야합니다. 이것은 호출자 실행 핸들러보다 낫습니다.
BlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(100);
// NOTE: you want the min and max thread numbers here to be the same value
ThreadPoolExecutor threadPool =
new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, queue);
// we need our RejectedExecutionHandler to block if the queue is full
threadPool.setRejectedExecutionHandler(new RejectedExecutionHandler() {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
try {
// this will block the producer until there's room in the queue
executor.getQueue().put(r);
} catch (InterruptedException e) {
throw new RejectedExecutionException(
"Unexpected InterruptedException", e);
}
}
});
// now read in the urls
while ((String url = urlReader.readLine()) != null) {
// submit them to the thread-pool. this may block.
threadPool.submit(new DownloadUrlRunnable(url));
}
// after we submit we have to shutdown the pool
threadPool.shutdown();
// wait for them to complete
threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
...
private class DownloadUrlRunnable implements Runnable {
private final String url;
public DownloadUrlRunnable(String url) {
this.url = url;
}
public void run() {
// download the URL
}
}
큰 파일에는 몇 개의 URL이 있습니까? – Steve
'수백만 줄'이란 말은 수백만 개의 URL을 의미합니다 ... – talnicolas
수백만 개의 데이터가 URL + HTTP 본문의 나머지 부분에 어셈블됩니다. – Nick