tags:

views:

158

answers:

3

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.

A: 

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.

jarnbjo
Is this documented somewhere? I found nothing about threadsafety in the JDK docs of java.net.Socket. Generally things are not guaranteed to be threadsafe unless explicitly stated.As both streams are just proxy objects to the underlying socket, one must assume that it is not safe to simultaneously access them from different threads unless the docs say otherwise.
Gerald Thaler
Gerald: That's not entirely true, the JavaDocs are often inconclusive when it comes to defining thread safety. Some times thread safety is stated, some times the lack of thread safety is explicitly mentioned. The documentation for java.net.Socket mentions neither. But as you state in your question, requiring synchronized access to both directions of a socket simultaneously would be unreasonable.
jarnbjo
+2  A: 

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.

erickson
A: 

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.

Jherico