Skip to content

Commit ca1f335

Browse files
committed
Closing MongoCursor in a finally block in OperationIterable.first and OperationIterable.forEach, to protect against exceptions.
JAVA-1846
1 parent 7b49445 commit ca1f335

File tree

1 file changed

+14
-6
lines changed

1 file changed

+14
-6
lines changed

driver/src/main/com/mongodb/OperationIterable.java

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -49,11 +49,15 @@ public MongoCursor<T> iterator() {
4949

5050
@Override
5151
public T first() {
52-
MongoCursor<T> iterator = iterator();
53-
if (!iterator.hasNext()) {
54-
return null;
52+
MongoCursor<T> cursor = iterator();
53+
try {
54+
if (!cursor.hasNext()) {
55+
return null;
56+
}
57+
return cursor.next();
58+
} finally {
59+
cursor.close();
5560
}
56-
return iterator.next();
5761
}
5862

5963
@Override
@@ -64,8 +68,12 @@ public <U> MongoIterable<U> map(final Function<T, U> mapper) {
6468
@Override
6569
public void forEach(final Block<? super T> block) {
6670
MongoCursor<T> cursor = iterator();
67-
while (cursor.hasNext()) {
68-
block.apply(cursor.next());
71+
try {
72+
while (cursor.hasNext()) {
73+
block.apply(cursor.next());
74+
}
75+
} finally {
76+
cursor.close();
6977
}
7078
}
7179

0 commit comments

Comments
 (0)