gpt4 book ai didi

java - 为什么 mongo 弃用了 MongoIterable.forEach(Block)?

转载 作者:行者123 更新时间:2023-11-30 05:47:35 27 4
gpt4 key购买 nike

MongoIterable 有两个 forEach 方法:

Iterable.forEach(Consumer)
MongoIterable.forEach(Block)

在最新版本的 mongo java 驱动程序中,MongoIterable.forEach 已被弃用,并发出通知称用户应切换到 Iterable.forEach

但是,MongoIterable.forEach 方法是在主实现类中实现的,或多或少如下所示:

try (MongoCursor<TResult> cursor = iterator()) {
while (cursor.hasNext()) {
block.apply(cursor.next());
}
}

并且没有相应的 Iterable.forEach 重写。这意味着 Iterable.forEach 泄漏了一个未关闭的 MongoCursor,因此,如果遵循弃用注释,则将通过更改来泄漏大量游标到Iterable.forEach

那么当替换泄漏游标对象时,为什么 MongoIterable.forEach 被标记为已弃用?

最佳答案

https://jira.mongodb.org/browse/JAVA-3046 ,说明了变化的主要原因:

The forEach(Block block) method on MongoIterable conflicts with the default forEach method added to java.lang.Iterable in Java 8. If you try to use either with a lambda expression you get a compiler error which forces you to cast the lambda to either Block or Consumer, which is not intuitive.

The default forEach method in Iterable, though, is dangerous to use with MongoIterable because it's not possible for it to force the MongoCursor to be closed in the case where Consumer.accept throws an exception, but in scope of JAVA-2010 we plan to address that. Given that, it makes sense to deprecate MongoIterable#forEach(Block block) so that it can be removed in the next major release and users will stop getting the compiler error.

关于java - 为什么 mongo 弃用了 MongoIterable.forEach(Block)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54579054/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com