@@ -112,16 +112,14 @@ class QueryBatchCursor<T> implements AggregateResponseBatchCursor<T> {
112112
113113 initFromQueryResult (firstQueryResult );
114114 firstBatchEmpty = firstQueryResult .getResults ().isEmpty ();
115- if (limitReached ()) {
116- killCursor (connection );
117- }
118- if (serverCursor == null && this .connectionSource != null ) {
119- this .connectionSource .release ();
120- this .connectionSource = null ;
121- }
115+
122116 if (connection != null ) {
123117 this .maxWireVersion = connection .getDescription ().getMaxWireVersion ();
118+ if (limitReached ()) {
119+ killCursor (connection );
120+ }
124121 }
122+ releaseConnectionSourceIfNoServerCursor ();
125123 }
126124
127125 @ Override
@@ -283,12 +281,9 @@ private void getMore() {
283281 if (limitReached ()) {
284282 killCursor (connection );
285283 }
286- if (serverCursor == null ) {
287- this .connectionSource .release ();
288- this .connectionSource = null ;
289- }
290284 } finally {
291285 connection .release ();
286+ releaseConnectionSourceIfNoServerCursor ();
292287 }
293288 }
294289
@@ -343,13 +338,23 @@ private void killCursor() {
343338 private void killCursor (final Connection connection ) {
344339 if (serverCursor != null ) {
345340 notNull ("connection" , connection );
346- if (serverIsAtLeastVersionThreeDotTwo (connection .getDescription ())) {
347- connection .command (namespace .getDatabaseName (), asKillCursorsCommandDocument (), NO_OP_FIELD_NAME_VALIDATOR ,
348- ReadPreference .primary (), new BsonDocumentCodec (), connectionSource .getSessionContext ());
349- } else {
350- connection .killCursor (namespace , singletonList (serverCursor .getId ()));
341+ try {
342+ if (serverIsAtLeastVersionThreeDotTwo (connection .getDescription ())) {
343+ connection .command (namespace .getDatabaseName (), asKillCursorsCommandDocument (), NO_OP_FIELD_NAME_VALIDATOR ,
344+ ReadPreference .primary (), new BsonDocumentCodec (), connectionSource .getSessionContext ());
345+ } else {
346+ connection .killCursor (namespace , singletonList (serverCursor .getId ()));
347+ }
348+ } finally {
349+ serverCursor = null ;
351350 }
352- serverCursor = null ;
351+ }
352+ }
353+
354+ private void releaseConnectionSourceIfNoServerCursor () {
355+ if (serverCursor == null && connectionSource != null ) {
356+ connectionSource .release ();
357+ connectionSource = null ;
353358 }
354359 }
355360
0 commit comments