56

Is it possible to have one thread write to the OutputStream of a Java Socket, while another reads from the socket's InputStream, without the threads having to synchronize on the socket?

Adam Gent
  • 47,843
  • 23
  • 153
  • 203
Tony the Pony
  • 40,327
  • 71
  • 187
  • 281
  • 8
    I wish this sort of information was readily available to developers via the Javadoc. – mre Jun 07 '11 at 13:23
  • 1
    at of curiosity what are you trying to do? If you are looking to do non blocking networking have you checked out http://mina.apache.org/ ? It probably doesn't fit your needs but worth looking at. – Adam Gent Jun 07 '11 at 13:49
  • @Adam: Thanks for the link, the Mina framework is probably more extensive than the simple IPC in my case. – Tony the Pony Jun 07 '11 at 14:59
  • 1
    "threadsafe" is not a proper term here. it's more like "full duplex". it's safe to have 2 threads, one for read, one for write. – irreputable Jun 07 '11 at 13:39

2 Answers2

48

Sure. The exact situation you're describing shouldn't be a problem (reading and writing simultaneously).

Generally, the reading thread will block if there's nothing to read, and might timeout on the read operation if you've got a timeout specified.

Since the input stream and the output stream are separate objects within the Socket, the only thing you might concern yourself with is, what happens if you had 2 threads trying to read or write (two threads, same input/output stream) at the same time? The read/write methods of the InputStream/OutputStream classes are not synchronized. It is possible, however, that if you're using a sub-class of InputStream/OutputStream, that the reading/writing methods you're calling are synchronized. You can check the javadoc for whatever class/methods you're calling, and find that out pretty quick.

jefflunt
  • 33,527
  • 7
  • 88
  • 126
  • I don't understand how both are possible simultaneously since `accept()` method (in case of ServerSocket) is a blocking method... So reading/writing thread can't acquire the socket at the same time.... Nevertheless, if I'm mistaken, do sent/received data not mixed up in the pipe ? – Jason Krs Mar 03 '18 at 10:34
  • accept() creates a new client socket. That's separate from reading/writing. Also there's two streams - an input stream and an output stream - so the data doesn't mix. – jefflunt Mar 03 '18 at 13:06
  • Okay..two streams!! I understand it better now... Thank You – Jason Krs Mar 03 '18 at 13:30
9

Yes, that's safe.

If you wanted more than one thread reading from the InputStream you would have to be more careful (assuming you are reading more than one byte at a time).

Paul Cager
  • 1,910
  • 14
  • 21