in what way is java.net.Socket threadsafe?

Viewed 14622

I have a Socket that I am both reading and writing to, via BufferedReaders and BufferedWriters. I'm not sure which operations are okay to do from separate threads. I would guess that writing to the socket from two different threads at the same time is a bad idea. Same with reading off the socket from two different threads at the same time. What about reading on one thread while writing on another?

I ask because I want to have one thread blocked for a long time on a read as it waits for more data, but during this wait I also have occasional data to send on the socket. I'm not clear if this is threadsafe, or if I should cancel the read before I write (which would be annoying).

6 Answers

Very interesting, the nio SocketChannel writes are synchronized

http://www.docjar.com/html/api/sun/nio/ch/SocketChannelImpl.java.html

The old io Socket stuff depends on the OS so you would have to look at the OS native code to know for sure(and that may vary from OS to OS)...

Just look at java.net.SocketOutputStream.java which is what Socket.getOutputStream returns.

(unless of course I missed something).

oh, one more thing, they could have put synchronization in the native code in every JVM on each OS but who knows for sure. Only the nio is obvious that synchronization exists.

Related