Skip to content

Commit f7a2779

Browse files
committed
Mark the QueryBatchCursor closed before calling killCursor
This ensures if there is an error killing the cursor subsequent calls to the cursor will act as expected for a closed cursor. JAVA-2379
1 parent aa0adf0 commit f7a2779

File tree

2 files changed

+41
-10
lines changed

2 files changed

+41
-10
lines changed

driver-core/src/main/com/mongodb/operation/QueryBatchCursor.java

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -141,18 +141,16 @@ public void remove() {
141141

142142
@Override
143143
public void close() {
144-
if (closed) {
145-
return;
146-
}
147-
try {
148-
killCursor();
149-
} finally {
150-
if (connectionSource != null) {
151-
connectionSource.release();
144+
if (!closed) {
145+
closed = true;
146+
try {
147+
killCursor();
148+
} finally {
149+
if (connectionSource != null) {
150+
connectionSource.release();
151+
}
152152
}
153153
}
154-
155-
closed = true;
156154
}
157155

158156
@Override

driver-core/src/test/unit/com/mongodb/operation/QueryBatchCursorSpecification.groovy

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
package com.mongodb.operation
1818

1919
import com.mongodb.MongoNamespace
20+
import com.mongodb.MongoSocketException
2021
import com.mongodb.ServerAddress
2122
import com.mongodb.binding.ConnectionSource
2223
import com.mongodb.connection.Connection
@@ -82,4 +83,36 @@ class QueryBatchCursorSpecification extends Specification {
8283
2 | 0 | null
8384
0 | 100 | 100
8485
}
86+
87+
def 'should handle exceptions when closing'() {
88+
given:
89+
def serverAddress = new ServerAddress()
90+
def connection = Mock(Connection) {
91+
_ * getDescription() >> Stub(ConnectionDescription) {
92+
getServerVersion() >> new ServerVersion([3, 2, 0])
93+
}
94+
_ * killCursor(_, _) >> { throw new MongoSocketException('No MongoD', serverAddress) }
95+
96+
}
97+
def connectionSource = Stub(ConnectionSource) {
98+
getConnection() >> { connection }
99+
}
100+
connectionSource.retain() >> connectionSource
101+
102+
def namespace = new MongoNamespace('test', 'QueryBatchCursorSpecification')
103+
def firstBatch = new QueryResult(namespace, [], 42, serverAddress)
104+
def cursor = new QueryBatchCursor<Document>(firstBatch, 0, 2, 100, new BsonDocumentCodec(), connectionSource, connection)
105+
106+
when:
107+
cursor.close()
108+
109+
then:
110+
thrown(MongoSocketException)
111+
112+
when:
113+
cursor.close()
114+
115+
then:
116+
notThrown(Exception)
117+
}
85118
}

0 commit comments

Comments
 (0)