Skip to content

Commit 2b7d18b

Browse files
close unclosed socket channels if any
1 parent 41f3436 commit 2b7d18b

File tree

1 file changed

+13
-0
lines changed

1 file changed

+13
-0
lines changed

utils/src/main/java/com/cloud/utils/nio/NioConnection.java

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333
import java.nio.channels.ServerSocketChannel;
3434
import java.nio.channels.SocketChannel;
3535
import java.util.ArrayList;
36+
import java.util.HashSet;
3637
import java.util.Iterator;
3738
import java.util.List;
3839
import java.util.Set;
@@ -75,6 +76,7 @@ public abstract class NioConnection implements Callable<Boolean> {
7576
protected ExecutorService _executor;
7677
protected ExecutorService _sslHandshakeExecutor;
7778
protected CAService caService;
79+
protected Set<SocketChannel> socketChannels = new HashSet<>();
7880

7981
public NioConnection(final String name, final int port, final int workers, final HandlerFactory factory) {
8082
_name = name;
@@ -230,6 +232,7 @@ public void run() {
230232
link.setSSLEngine(sslEngine);
231233
link.setKey(socketChannel.register(key.selector(), SelectionKey.OP_READ, link));
232234
final Task task = _factory.create(Task.Type.CONNECT, link, null);
235+
socketChannels.add(socketChannel);
233236
registerLink(saddr, link);
234237
_executor.submit(task);
235238
} catch (IOException e) {
@@ -496,6 +499,16 @@ public void close(final SelectionKey key) {
496499

497500
/* Release the resource used by the instance */
498501
public void cleanUp() throws IOException {
502+
for (SocketChannel channel : socketChannels) {
503+
if (channel != null && channel.isOpen()) {
504+
try {
505+
logger.info(String.format("Closing connection: %s", channel.getRemoteAddress()));
506+
channel.close();
507+
} catch (IOException e) {
508+
logger.warn(String.format("Unable to close connection due to %s", e.getMessage()));
509+
}
510+
}
511+
}
499512
if (_selector != null) {
500513
_selector.close();
501514
}

0 commit comments

Comments
 (0)