@@ -413,9 +413,7 @@ private Socket connectToLeader() throws IOException, X509Exception, InterruptedE
413413 for (int tries = 0 ; tries < 5 ; tries ++) {
414414 try {
415415 sock = createSocket ();
416- if (socket .get () == null ) {
417- continue ;
418- }
416+
419417 // recalculate the init limit time because retries sleep for 1000 milliseconds
420418 remainingTimeout = connectTimeout - (int ) ((nanoTime () - startNanoTime ) / 1_000_000 );
421419 if (remainingTimeout <= 0 ) {
@@ -427,34 +425,29 @@ private Socket connectToLeader() throws IOException, X509Exception, InterruptedE
427425 if (self .isSslQuorum ()) {
428426 ((SSLSocket ) sock ).startHandshake ();
429427 }
430- sock .setTcpNoDelay (nodelay );
431- break ;
432428 } catch (IOException e ) {
429+ // close failed socket before retrying
430+ if (sock != null ) {
431+ try {
432+ sock .close ();
433+ } catch (IOException closeException ) {
434+ LOG .debug ("Failed to close socket after connection failure" , closeException );
435+ }
436+ sock = null ;
437+ }
433438 remainingTimeout = connectTimeout - (int ) ((nanoTime () - startNanoTime ) / 1_000_000 );
434439
435440 if (remainingTimeout <= leaderConnectDelayDuringRetryMs ) {
436- LOG .error (
437- "Unexpected exception, connectToLeader exceeded. tries={}, remaining init limit={}, connecting to {}" ,
438- tries ,
439- remainingTimeout ,
440- address ,
441- e );
441+ LOG .error ("Unexpected exception, connectToLeader exceeded. tries={}, remaining init limit={}, connecting to {}" ,
442+ tries , remainingTimeout , address , e );
442443 throw e ;
443444 } else if (tries >= 4 ) {
444- LOG .error (
445- "Unexpected exception, retries exceeded. tries={}, remaining init limit={}, connecting to {}" ,
446- tries ,
447- remainingTimeout ,
448- address ,
449- e );
445+ LOG .error ("Unexpected exception, retries exceeded. tries={}, remaining init limit={}, connecting to {}" ,
446+ tries , remainingTimeout , address , e );
450447 throw e ;
451448 } else {
452- LOG .warn (
453- "Unexpected exception, tries={}, remaining init limit={}, connecting to {}" ,
454- tries ,
455- remainingTimeout ,
456- address ,
457- e );
449+ LOG .warn ("Unexpected exception, tries={}, remaining init limit={}, connecting to {}" ,
450+ tries , remainingTimeout , address , e );
458451 }
459452 }
460453 Thread .sleep (leaderConnectDelayDuringRetryMs );
0 commit comments