首页 > 应用开发 > Java > ArrayList 的线程安全问题
java.util.ConcurrentModificationException: null at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909) ~[?:1.8.0_181] at java.util.ArrayList$Itr.next(ArrayList.java:859) ~[?:1.8.0_181] at com.vsoc.realtime.schedule.functions.PostgreSQLSinkFunction.flush(PostgreSQLSinkFunction.java:199) ~[blob_p-87058e81471573bdb6638bc203aad50c09ce387c-f9f70b611eeba0339b2421e8d3b249d4:?] at com.vsoc.realtime.schedule.functions.PostgreSQLSinkFunction.lambda$open$0(PostgreSQLSinkFunction.java:88) ~[blob_p-87058e81471573bdb6638bc203aad50c09ce387c-f9f70b611eeba0339b2421e8d3b249d4:?] at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) [?:1.8.0_181] at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308) [?:1.8.0_181] at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:180) [?:1.8.0_181] at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:294) [?:1.8.0_181] at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [?:1.8.0_181] at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [?:1.8.0_181] at java.lang.Thread.run(Thread.java:748) [?:1.8.0_181]
错误原因:
在SinkFunction函数里面,使用List不当的话,可能会导致线程安全问题,比如,配置了一个定时任务,定时遍历获取数据,但是另外一个地方在往这个List里面写数据,这种情况,就可能会导致线程安全问题。
解决方案 :
//Collections.synchronizedList
buffer = Collections.synchronizedList(new ArrayList<>());
private void flush() {
// synchronized
synchronized (buffer) {
//
......
}
}
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/70024433/viewspace-3002760/ ,如需转载,请注明出处,否则将追究法律责任。