I'm writing a Java application that uses NIO sockets. It consists of 3 servers and a set of clients. A client can communicate with a server, and a server can communicate with a client and the other servers.
Servers to servers and clients to servers sends Messages that are serialize to a byte[] array. The first byte of each Message contains the size of the message and naturally it is guaranteed that each message does not contain more than 127 (2^8 -1) bytes.
You can think of the sending of messages of the servers and the clients as operating in a loop:
Message msg = new Message()
while (true) {
sendMessage(msg, server or client)
receiveMessage()
}
Then, the implementation utilizes ByteBuffer. Naturally, as in any Java NIO implementation, each server does selector.select() and then retrieves the SelectionKeys to see if reading (calling handleRead() method), writeing (calling handleWrite()), or accepting (calling handleAccept()) needs to be handled. All the handleXX methods take a finite number of steps and do not block waiting for anything else.
When retrieving the data (handleRead()) for a specific key, I just store the data in a specific map Map<SelectionKey, List<byte[]>> readDataForKey; Then I traverse the list and extract all the messages that have been received.
However, I noticed that sometimes when entering handleRead for some key there are thousands of messages waiting to be processed. I cannot figure out why this would be the case?
I would expect handleRead to see a couple of messages and that would be it.
The fact that some times thousand of messages get accumulated before they are being processed. What does that mean? Does it mean that my handleRead or handleWrite or some other part of the NIO implementation takes too long and the underlying buffers get full? Does it mean that once in a while I get a GC even (for ~10ms) and in the meantime the buffers get full? Does it mean that I have code that is perhaps slow in handleRead and therefore the messages get accumulated?
Is it normal for so many messages to accumulate?