Skip to content

Commit 6076d61

Browse files
committed
JAVA-2778: Add Javadoc for cursors indicating that they should be closed using, for example, try-with-resources.
1 parent 4976da5 commit 6076d61

File tree

2 files changed

+21
-7
lines changed

2 files changed

+21
-7
lines changed

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

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -36,13 +36,16 @@
3636
import static java.util.concurrent.TimeUnit.MILLISECONDS;
3737

3838
/**
39-
* <p>An iterator over database results. Doing a {@code find()} query on a collection returns a {@code DBCursor} thus</p>
40-
* <pre>
41-
* DBCursor cursor = collection.find(query);
42-
* if(cursor.hasNext()) {
43-
* DBObject obj = cursor.next();
39+
* <p>An iterator over database results. Doing a {@code find()} query on a collection returns a {@code DBCursor}.</p>
40+
* <p> An application should ensure that a cursor is closed in all circumstances, e.g. using a try-with-resources statement:</p>
41+
* <blockquote><pre>
42+
* try (DBCursor cursor = collection.find(query)) {
43+
* while (cursor.hasNext()) {
44+
* System.out.println(cursor.next();
45+
* }
4446
* }
45-
* </pre>
47+
* </pre></blockquote>
48+
*
4649
* <p><b>Warning:</b> Calling {@code toArray} or {@code length} on a DBCursor will irrevocably turn it into an array. This means that, if
4750
* the cursor was iterating over ten million results (which it was lazily fetching from the database), suddenly there will be a ten-million
4851
* element array in memory. Before converting to an array, make sure that there are a reasonable number of results using {@code skip()} and

driver/src/main/com/mongodb/client/MongoCursor.java

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,13 +24,24 @@
2424
import java.util.Iterator;
2525

2626
/**
27-
* The Mongo Cursor interface implementing the iterator protocol
27+
* The Mongo Cursor interface implementing the iterator protocol.
28+
* <p>
29+
* An application should ensure that a cursor is closed in all circumstances, e.g. using a try-with-resources statement:
30+
*
31+
* <blockquote><pre>
32+
* try (MongoCursor&lt;Document&gt; cursor = collection.find().iterator()) {
33+
* while (cursor.hasNext()) {
34+
* System.out.println(cursor.next());
35+
* }
36+
* }
37+
* </pre></blockquote>
2838
*
2939
* @since 3.0
3040
* @param <TResult> The type of documents the cursor contains
3141
*/
3242
@NotThreadSafe
3343
public interface MongoCursor<TResult> extends Iterator<TResult>, Closeable {
44+
3445
@Override
3546
void close();
3647

0 commit comments

Comments
 (0)