0
votes

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:

  1. Pop a thread and wait a few milliseconds before closing.
  2. 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"

Anyway, I feel both ways are dirty. Is there an elegant way to deal with this issue?

Code:

String msg = "byebye";
channel.write(ByteBuffer.wrap(msg.getBytes()));
channel.close();
1

1 Answers

1
votes

calling close() may cause the undergoing writing operation to throw a ClosedChannelException.

No it won't. That exception is thrown by the write() method. Once the write() method has exited it can't be thrown. The data remains in the kernel's socket output buffer for writing.