@@ -138,35 +138,41 @@ void close() {
138138 @ Override
139139 public void run () {
140140 ServerDescription currentServerDescription = getConnectingServerDescription (null );
141- while (!isClosed ) {
142- ServerDescription previousServerDescription = currentServerDescription ;
143- currentServerDescription = lookupServerDescription (currentServerDescription );
141+ try {
142+ while (!isClosed ) {
143+ ServerDescription previousServerDescription = currentServerDescription ;
144+ currentServerDescription = lookupServerDescription (currentServerDescription );
144145
145- if (isClosed ) {
146- continue ;
147- }
146+ if (isClosed ) {
147+ continue ;
148+ }
148149
149- if (currentCheckCancelled ) {
150- waitForNext ();
151- currentCheckCancelled = false ;
152- continue ;
153- }
150+ if (currentCheckCancelled ) {
151+ waitForNext ();
152+ currentCheckCancelled = false ;
153+ continue ;
154+ }
154155
155- logStateChange (previousServerDescription , currentServerDescription );
156- serverStateListener .stateChanged (new ChangeEvent <>(previousServerDescription , currentServerDescription ));
156+ logStateChange (previousServerDescription , currentServerDescription );
157+ serverStateListener .stateChanged (new ChangeEvent <>(previousServerDescription , currentServerDescription ));
157158
158- if (currentServerDescription .getException () != null ) {
159- connectionPool .invalidate ();
160- }
159+ if (currentServerDescription .getException () != null ) {
160+ connectionPool .invalidate ();
161+ }
161162
162- if (((connection == null || shouldStreamResponses (currentServerDescription ))
163- && currentServerDescription .getTopologyVersion () != null )
164- || (connection != null && connection .hasMoreToCome ())
165- || (currentServerDescription .getException () instanceof MongoSocketException
166- && previousServerDescription .getType () != UNKNOWN )) {
167- continue ;
163+ if (((connection == null || shouldStreamResponses (currentServerDescription ))
164+ && currentServerDescription .getTopologyVersion () != null )
165+ || (connection != null && connection .hasMoreToCome ())
166+ || (currentServerDescription .getException () instanceof MongoSocketException
167+ && previousServerDescription .getType () != UNKNOWN )) {
168+ continue ;
169+ }
170+ waitForNext ();
171+ }
172+ } finally {
173+ if (connection != null ) {
174+ connection .close ();
168175 }
169- waitForNext ();
170176 }
171177 }
172178
0 commit comments