SocketChannel.write will in non-blocking mode return the number of bytes that can be immediately sent to the network without blocking. Your question makes me think that you expect the write method to consume the entire buffer and try to send additional data asynchronously to the network, but that’s not how it works.
If you really need to make sure that an error message is sent to the client before disconnecting the socket, I would simply enable the lock before calling the write method. Using non-blocking mode, you have to call the record in a loop, counting the number of bytes sent by each call, and exit the loop when you manage to send the entire message to the socket (a bad decision, I know, unnecessary code, waiting for waiting, etc.) .