I want to close Java non blocking socket channel after writing a string byebye. However, methods in non blocking mode are returned immediately, so calling close() may cause the undergoing writing operation to throw a ClosedChannelException.
I can think of 2 workarounds:
- Pop a thread and wait a few milliseconds before closing.
- Switch to blocking mode before closing, but Java doc says
"A channel must be placed into non-blocking mode before being registered with a selector, and may not be returned to blocking mode until it has been deregistered"
Code:
String msg = "byebye";
channel.write(ByteBuffer.wrap(msg.getBytes()));
channel.close();