1

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 ?

Dunxton
  • 408
  • 1
  • 8
  • 21

2 Answers2

3

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

Konstantin Pribluda
  • 12,329
  • 1
  • 30
  • 35
  • But the OS does just this right ? It has a fixed number of ports (say 65000) and reuses the ports from this pool. Y should I implement the same thing at a micro level ? – Dunxton Nov 14 '11 at 05:46
  • It is copstly to have OS open news socket, so it is best to keep and reuse existing one ( opening new socked means TCP hanshaking with server ) – Konstantin Pribluda Nov 14 '11 at 07:55
1

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.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • 100-200 processes, each spawning 3 connections,so in effect it is around 600 socket connections a second. What about these NIO frameworks like apache MINA or Jboss netty ? Will they help ? I am a little concerned with pooling because I cannot afford reconnection or thread wait/blocking. It has to be real time data that I send. Besides, I can only write the socket client. The destinations are not in my control to read data in batches. – Dunxton Nov 14 '11 at 05:50
  • Sending one message per connection is bound to be very inefficient. The overhead is more than 1000x higher than re-using an existing connection. It also places an enormous burden on the server. You could cause it to run out of resources if you are not careful. If you really have to re-connect each time you will have to determine through experimentation what is the limit at which you can do this and limit your clients collectively to this rate. You are better off trying to convince whomever manages the server to fix it or at least warn them they need to tell you if you bring down the server. – Peter Lawrey Nov 14 '11 at 07:05