Question

My java application has to send messages(multithreaded) to a socket server. The application can send around 100-200 messages a second.

I want to know which is a better approach to do this ?

  1. Open a single client socket and send the message from all threads though this one socket. Disadvantages: Have to handle the reconnection logic on connection failure,may lose many messages when reconnection is in process.Thread safety, blocking ??
  2. Create a new client socket connection for each thread and close it after sending. Disadvantages: Even though I close the socket, the ports will wait till the TIME_WAIT period.

Which is a better practical approach ?

Was it helpful?

Solution

I would propose 3. : Open an socket per thread, and reuse threads (for example via thread pool). Then handle reconnection inside thread, or just dispose it properly and create new one. This way you can avoid blocking and synchronisation issues

OTHER TIPS

100-200 messages per second isn't that much. I wouldn't re-connect every time as this is expensive. If you re-use your connection, it will be much faster.

If you are worried about losing messages, you can send a batch of messages or one at a time and wait for a confirmation from the server they have been received. You can still send thousands of messages per second this way.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top