我打算使用 parallelStream 执行一些耗时的代码。这似乎工作良好,但我有一个问题,即后续代码未执行:
@PreDestroy
public void tearDown() {
final int mapSize = eventStreamProcessorMap.size();
LOG.info("There are {} subscriptions to be stopped!", mapSize);
final long start = System.currentTimeMillis();
LocalTime time = LocalTime.now();
final AtomicInteger count = new AtomicInteger();
eventStreamProcessorMap.entrySet().parallelStream().forEach(entry -> {
final Subscription sub = entry.getKey();
final StreamProcessor processor = entry.getValue();
LOG.info("Attempting to stop subscription {} of {} with id {} at {}", count.incrementAndGet(), mapSize, sub.id(), LocalTime.now().format(formatter));
LOG.info("Stopping processor...");
processor.stop();
LOG.info("Processor stopped.");
LOG.info("Removing subscription...");
eventStreamProcessorMap.remove(sub);
LOG.info("Subscription {} removed.", sub.id());
LOG.info("Finished stopping processor {} with subscription {} in ParallelStream at {}: ", processor, sub, LocalTime.now().format(formatter));
LOG.info(String.format("Duration: %02d:%02d:%02d:%03d (hh:mm:ss:SSS)",
TimeUnit.MILLISECONDS.toHours(System.currentTimeMillis() - start),
TimeUnit.MILLISECONDS.toMinutes(System.currentTimeMillis() - start)%60,
TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - star0)%60,
TimeUnit.MILLISECONDS.toMillis(System.currentTimeMillis() - start)%1000));
LOG.info("--------------------------------------------------------------------------");
});
LOG.info("Helloooooooooooooo?????");
LOG.info(String.format("Overall shutdown duration: %02d:%02d:%02d:%03d (hh:mm:ss:SSS)",
TimeUnit.MILLISECONDS.toHours(System.currentTimeMillis() - start),
TimeUnit.MILLISECONDS.toMinutes(System.currentTimeMillis() - start)%60,
TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - start)%60,
TimeUnit.MILLISECONDS.toMillis(System.currentTimeMillis() - start)%1000));
LOG.info("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
}
parallelStream处理后的代码未执行:
LOG.info("Helloooooooooooooo?????");
永远不会出现在日志中。为什么不呢?
答案 0 :(得分:1)
这是由eventStreamProcessorMap.remove(sub);
引起的(您现在通过所做的编辑将其从代码中删除)。您正在通过Map
entrySet(eventStreamProcessorMap
)流式传输并从中删除元素-这是不允许的,这就是为什么要获得ConcurrentModificationException
的原因。
如果您确实要在迭代时删除,请使用Iterator
或map.entrySet().removeIf(x -> {...})