java - 在这种情况下如何清除 ArrayList 的大小(如果为 100):

标签 java concurrentmodification

我的最终目标是在执行器服务中实现行的批量处理。我有以下代码片段:

while ((bLine = bufferedReader.readLine()) != null) {
    // We will use an array to hold 100 lines, so that we can batch process in a
    // single thread
    batchArray.add(bLine);
    switch (batchArray.size()) {
        case 100:
            Future<?> future = executor.submit(new LocalThreadPoolExecutor(batchArray, closeableHttpClient, httpPost));
            futures.add(future);
           // batchArray.clear() <--- point of failure
            break;
        default:
            logger.info("Batch size in switch: "+batchArray.size());

    }
}

现在,如果我在 case 100 中执行 batchArray.clear(),我会得到一个并发修改异常。无法确定如何重新初始化数组列表并将 100 行发送到我的执行程序,因为它们是从文件中读取的。

下面是堆栈跟踪:

java.util.ConcurrentModificationException
    at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:859)
    at java.util.ArrayList$Itr.next(ArrayList.java:831)
    at consumer.ril.com.LocalThreadPoolExecutor.run(LocalThreadPoolExecutor.java:37)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)

当我尝试读取在此类的构造函数中传递的batchArray 时,我在LocalThreadPoolExecutor 类中遇到异常。

最佳答案

简单的解决方案 - 您需要传递给 LocalThreadPoolExecutor 数组副本并清理原始数组。

Future<?> future = executor.submit(new LocalThreadPoolExecutor(new ArrayList<>
(batchArray), closeableHttpClient, httpPost));
futures.add(future);
batchArray.clear();

关于java - 在这种情况下如何清除 ArrayList 的大小(如果为 100):,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44265904/

相关文章:

java - 迭代器但仍然 ConcurrentModificationException

postgresql - 为什么不能在表上并行执行 truncate 和 grant 语句?

java - 为什么我的示例不抛出 ConcurrentModificationException

java - 对话框中的取消按钮不关闭对话框

java - 在 ant build.xml 文件中检索类路径值

java - 如何传递 ehcache.xml 中声明的 ehCache 装饰器中的依赖项

java - 使用包含 (? :. |\s)*? 的模式进行正则表达式搜索需要越来越长的时间

Java - 奇怪的ConcurrentModificationException

java - 如何在避免 ConcurrentModificationException 的同时遍历 HashMap

java - 如何对齐 JPanel 中的 3 个 JLabel 的底部