From 7427d4e2dd3cfc345e09a75898006baadf32a489 Mon Sep 17 00:00:00 2001 From: Jooyoung Pyoung Date: Sat, 7 Dec 2024 06:59:19 +0900 Subject: [PATCH] GH-9694: Remove duplicate SocketChannel initialization Fixes: #9694 Issue link: https://github.com/spring-projects/spring-integration/issues/9694 - Add null check before closing `socketChannel` in catch block - Prevents potential `NullPointerException` during error handling **Auto-cherry-pick to `6.3.x`** --- .../connection/TcpNioClientConnectionFactory.java | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/spring-integration-ip/src/main/java/org/springframework/integration/ip/tcp/connection/TcpNioClientConnectionFactory.java b/spring-integration-ip/src/main/java/org/springframework/integration/ip/tcp/connection/TcpNioClientConnectionFactory.java index 00954ebc05..83a06f969a 100644 --- a/spring-integration-ip/src/main/java/org/springframework/integration/ip/tcp/connection/TcpNioClientConnectionFactory.java +++ b/spring-integration-ip/src/main/java/org/springframework/integration/ip/tcp/connection/TcpNioClientConnectionFactory.java @@ -40,6 +40,7 @@ import org.springframework.util.Assert; * @author Artem Bilan * @author Christian Tzolov * @author Ngoc Nhan + * @author Jooyoung Pyoung * * @since 2.0 * @@ -85,8 +86,9 @@ public class TcpNioClientConnectionFactory extends @Override protected TcpConnectionSupport buildNewConnection() { + SocketChannel socketChannel = null; try { - SocketChannel socketChannel = SocketChannel.open(); + socketChannel = SocketChannel.open(); setSocketAttributes(socketChannel.socket()); connect(socketChannel); TcpNioConnection connection = @@ -113,6 +115,14 @@ public class TcpNioClientConnectionFactory extends return wrappedConnection; } catch (IOException e) { + try { + if (socketChannel != null) { + socketChannel.close(); + } + } + catch (IOException e2) { + logger.error(e2, "Error closing socket channel"); + } throw new UncheckedIOException(e); } catch (InterruptedException e) {