繁体   English   中英

java Multithreading - 限制提交到ExecutorService

[英]java Multithreading - throttle submission to ExecutorService

我有一个包含数千行的数据文件。 我正在阅读它们并将它们保存在数据库中。 我想在50行的批量中多线程化这个过程。 正如我在文件中读到的那样,将10行提交给ExecutorService。

ExecutorService executor = Executors.newFixedThreadPool(5);`

我可以在下面的while循环中直到我的行结束....

 Future<Integer> future = executor.submit(callableObjectThatSaves10RowsAtOneTime);

但是,如果处理10行需要时间,我不想将整个文件读入内存。 我只想提交5,直到其中一个线程返回,然后我提交下一个。

假设一个线程需要20秒来保存10条记录,我不希望ExecutorService被馈送数千行,因为读取过程继续读取并提交给ExecutorService

实现这一目标的最佳方法是什么?

您可以使用LinkedList<Future<?>>来存储期货,直到达到某个预定的大小。 这里有一些骨架代码可以帮助你完成大部分工作:

int threads = 5;
ExecutorService service = Executors.newFixedThreadPool(threads);
LinkedList<Future<?>> futures = new LinkedList<>();

//As long as there are rows to save:
while(moreRowsLeft()){
    //dump another callable onto the queue:
    futures.addLast(service.submit(new RowSavingCallable());

    //if the queue is "full", wait for the next one to finish before
    //reading any more of the file:
    while(futures.size() >= 2*threads) futures.removeFirst().get();
}

//All rows have been submitted but some may still be writing to the DB:
for(Future<?> f : futures) future.get();

//All rows have been saved at this point

您可能想知道为什么我允许期货的数量达到机器上线程数的两倍 - 这允许执行程序服务线程处理数据库保存,而主线程正在创建更多工作要完成。 这可以帮助隐藏与在工作线程忙于执行数据库写入时使更多可用的处理器可用于处理相关的任何I / O开销。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM