synListItem = Collections.synchronizedList(new ArrayList < > ());
Iterator < Map < String, Object >> iterator = listItem.iterator();
while (iterator.hasNext()) {
try {
final Future < ? > future = ExecutorFactory.getEs().submit(()->{
Map < String,Object > map = iterator.next();
// 逻辑处理
synListItem.xxx
});
try {
future.get(threadTimeout, TimeUnit.SECONDS);
} catch (TimeoutException e) {
future.cancel(true);
log.error("timeout.....");
}
} catch (Exception e) {
e.printStackTrace();
}
}
基于上篇文章使用程序计数器去承接多个子线程解决性能差的远程网络I/O问题,但是发现会出现集合多线程情况下的未知情况:因为程序计数器只是对线程进行阻塞,当程序计数器减为0 或者 时间到时,子线程依旧在执行和主线程异步执行,如果子线程被修改的集合被下面执行的主线程调用,则会出现多线程问题
基于这个问题使用很多的解决方案,
- 使用List 遍历 future.get()
- 使用 CompletableFuture allFutures = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
但是发现性能都欠佳
最后压测和实验发现,一个线程处理其自己的线程性能最好,同时,异步等待超时,中断线程。
只能展示部分压测效果: