Hello,
I was working on a server that has to send the same message to all the connected clients, something like a broadcast.
I've noticed that the memory usage was going high very quickly and the garbage collection was happening too often.
Examining the code shows that in order to send a single byte array, a ByteBuffer object, a BinaryFrame, a List, an ArrayList and at least a new ByteBuffer is created.
So, in this case where one may want to send the exact same content to many clients I guess that it is better not to recreate the objects with the same content for each recipient.
A simple solution that I have in mind is making the write() method in WebSocketImpl public. Then one can create the message (List<ByteBuffer>) once and write it to each client. Here is an example:
public void broadcast(byte[] buffer, Collection<WebSocket> clients) {
if (!clients.isEmpty()) {
Draft draft = clients.iterator().next().getDraft();
List<Framedata> frames = draft.createFrames(ByteBuffer.wrap(buffer), true);
List<ByteBuffer> outgoingFrames = new ArrayList<ByteBuffer>();
for (Framedata f : frames) {
outgoingFrames.add(draft.createBinaryFrame(f));
}
for (WebSocket client : clients) {
client.write(outgoingFrames);
}
}
}
I have tested this thought and by profiling a test application it seems to works ok.
Do you find this approach ok? I don't fill comfortable making a private method public. Do you have any suggestions to achieve this in a better way?
Hello,
I was working on a server that has to send the same message to all the connected clients, something like a broadcast.
I've noticed that the memory usage was going high very quickly and the garbage collection was happening too often.
Examining the code shows that in order to send a single byte array, a ByteBuffer object, a BinaryFrame, a List, an ArrayList and at least a new ByteBuffer is created.
So, in this case where one may want to send the exact same content to many clients I guess that it is better not to recreate the objects with the same content for each recipient.
A simple solution that I have in mind is making the
write()method inWebSocketImplpublic. Then one can create the message (List<ByteBuffer>) once andwriteit to each client. Here is an example:I have tested this thought and by profiling a test application it seems to works ok.
Do you find this approach ok? I don't fill comfortable making a
privatemethodpublic. Do you have any suggestions to achieve this in a better way?