Skip to content

Commit ac22428

Browse files
committed
JAVA-1165 ensure array and itcount methods always close cursor server side even on IO error
1 parent 5ab8d22 commit ac22428

File tree

2 files changed

+29
-7
lines changed

2 files changed

+29
-7
lines changed

src/main/com/mongodb/DBCursor.java

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -602,8 +602,12 @@ public void remove(){
602602

603603
void _fill( int n ){
604604
_checkType( CursorType.ARRAY );
605-
while ( n >= _all.size() && _hasNext() )
606-
_next();
605+
try {
606+
while ( n >= _all.size() && _hasNext() )
607+
_next();
608+
} finally {
609+
this.close();
610+
}
607611
}
608612

609613
/**
@@ -649,12 +653,16 @@ public List<DBObject> toArray( int max ) {
649653
* @throws MongoException
650654
*/
651655
public int itcount(){
652-
int n = 0;
653-
while ( this.hasNext() ){
654-
this.next();
655-
n++;
656+
try {
657+
int n = 0;
658+
while ( this.hasNext() ){
659+
this.next();
660+
n++;
661+
}
662+
return n;
663+
} finally {
664+
this.close();
656665
}
657-
return n;
658666
}
659667

660668
/**

src/test/com/mongodb/DBCursorTest.java

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -674,6 +674,20 @@ public void testShowDiskLoc() {
674674
}
675675
}
676676

677+
@Test
678+
public void testToArrayCursorClosed() {
679+
final DBCollection c = collection;
680+
681+
// Insert some data.
682+
for (int i = 0; i < 4; i++) {
683+
c.insert(new BasicDBObject("one", "two"));
684+
}
685+
686+
final DBCursor cursor = c.find().batchSize(3); // ensure under normal conditions the cursor would remain
687+
cursor.toArray(3);
688+
assertEquals(0L, cursor.getCursorId());
689+
}
690+
677691
@Test(expected = MongoException.class)
678692
public void testSnapshotWithHint() {
679693
DBCursor cursor = new DBCursor(collection, new BasicDBObject(), new BasicDBObject(), ReadPreference.primary())

0 commit comments

Comments
 (0)