1

I have comeup with a multithreaded TCP server to handle reads and writes. My main objective is to separate out the reading and writing by two different threads. Hence I have a separate thread pool for writing to socket's outputstream. As soon as the read is finished by a thread and inserted into a queue (ArrayBlockingQueue), another thread from a pool will pick this up from the queue and write into the outputstream. Now the question is, I wanted to know when multiple threads try to write to the SAME socket's output stream; - how will be the behaviour - is this managed internally or needs to be handled specially - does the bytes gets messed (mixed) up

What would be a better approach in this case?

EDIT: My Question is not the same as, Are parallel calls to send/recv on the same socket valid?. The link is talking about POSIX and I forgot to mention that my question is specific about JAVA socket (socketWrite). To answer EJP's comment, yes, ours is a TCP protocol that has the use case of writing to the same output stream by multiple threads (to improve performance). Currently to solve my problem, I have synchronized outputstream;

synchronized (outputStream) {
    outputStream.write(responseMessage);
    outputStream.flush();
}
Community
  • 1
  • 1
  • Why would you want multiple threads to write to the same socket? And how will that arise n your architecture? What you want is one reading thread and one writing thread. – user207421 Jan 27 '17 at 16:08
  • I think the question is duplicate of the http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid – Zaboj Campula Jan 27 '17 at 20:40
  • Possible duplicate of [Are parallel calls to send/recv on the same socket valid?](http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid) – Zaboj Campula Jan 27 '17 at 20:40
  • Having multiple threads sending on the same socket without any synchronization is a bad idea, since (as you suspected) it means that data received by the remote client will be ordered in unpredictable ways, and therefore difficult/impossible to interpret reliably. You'd be better off dedicating a single thread to do all of the writing -- other threads can pass message-objects to this thread (e.g. via FIFO message queue) and it can then send the messages's contents on to the socket. – Jeremy Friesner Jan 28 '17 at 05:40
  • Thanks Jeremy. But what's the problem in having multiple threads writing into the socket in a synchronized block? – coderHASH64codingHASH46code Jan 28 '17 at 08:57

0 Answers0