2
votes

I have two separate java processes communicating over a single TCP connection. The protocol is not a simple synchronous request/response one like HTTP. Both sides may independently initiate requests and send data. I want to implement this using threads and blocking sockets, avoiding NIO. But is this even possible?

Java sockets (java.net.Socket) are not threadsafe, so i'm not allowed to read from the socket in one thread while simultaneously writing to it in another thread. (Is this true?) This restriction obviously leads to the possibility of deadlock, when both sides are blocked writing to the socket.

It follows that certain protocols on top of TCP can't be implemented in java without using NIO, or am i missing a point?

Thank you.

3

3 Answers

4
votes

Full duplex communication is certainly possible. Without NIO, you'll need a thread to read from the socket (and perform the requested processing). Meanwhile, another thread can be writing to the same socket.

If you can point out some documentation that suggests that sockets are not full duplex, I'll try to clarify it.

1
votes

I don't know where you've read that Java sockets are generally thread-unsafe. You can't have multiple threads simultaneously writing or reading from the socket's streams, but there's no reason why you can't have on thread writing to the socket's OutputStream and another thread reading from the socket's InputStream.

0
votes

Sockets are thread safe so there's no problem with using multiple threads, one for reading and one for writing. On the other hand if you want to avoid multiple threads then you need to perform polling on the socket input stream to see if there's incoming data on a regular basis while you're performing whatever outbound operations you have.