Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do Java sockets support full duplex?

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?

like image 513
Tony the Pony Avatar asked Jun 07 '11 13:06

Tony the Pony


People also ask

Does UDP support full duplex?

UDP, in the right circumstances, can be considered fully duplex, but by itself, it is not, whereas TCP, on the other hand, is always fully duplex. UDP is a fire-and-forget, best-effort protocol, but the upper layers can use it in a fully duplex fashion. TCP requires handshaking and other two-way communication.

What protocol do Java sockets use?

There are two communication protocols that we can use for socket programming: User Datagram Protocol (UDP) and Transfer Control Protocol (TCP).

What are the three types of sockets in Java?

Java provides three different types of sockets. Connection-oriented (TCP) sockets are implemented with the Socket class. Connectionless (UDP) sockets use the Datagramsocket class. A third type is the Multicastsocket class, which is a subclass of the DatagramSocket class.


2 Answers

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.

like image 192
jefflunt Avatar answered Oct 05 '22 21:10

jefflunt


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

like image 24
Paul Cager Avatar answered Oct 05 '22 21:10

Paul Cager