呼叫Java_使用Java处理HTTP呼叫的大文件

本文介绍了一种利用Java线程池和阻塞队列实现高效并行下载的方法。通过合理配置线程池参数及拒绝策略,可以有效地处理大量HTTP请求,避免一次性加载整个文件到内存中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

小编典典

我想并行化调用,但是不确定是否应该将整个文件读入内存

您应该使用ExecutorService与bounded的BlockingQueue。在读入百万行时,您将作业提交到线程池,直到作业BlockingQueue满为止。这样,您将能够同时运行100个(或最佳数量)的HTTP请求,而无需事先读取文件的所有行。

RejectedExecutionHandler如果队列已满,您将需要设置一个阻止的对象。这比调用方运行处理程序更好。

BlockingQueue queue = new ArrayBlockingQueue(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

}

}

2020-09-23

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值