Do Java sockets support full duplex?

JavaMultithreadingSockets

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

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).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTony the PonyView Question on Stackoverflow
Solution 1 - JavajeffluntView Answer on Stackoverflow
Solution 2 - JavaPaul CagerView Answer on Stackoverflow