Is a Java socket's PrintWriter thread safe?
It's a poor design to have these multiple PrintWriter
s on the same stream. Really you want at least the object the calls them to be synchronised (or thread confined).
However, assuming for some reason you do want multiple PrintWriter
s:
First problem: Writer
s do not use this
as the lock. PrintWriter
and BufferedWriter
by default both use the Writer
they are constructed with as the lock. This is obviously completely broken. They should be using the Writer
's lock, not the Writer
itself. An easy mistake given that having locking a feature of Object
removes static type safety. So you'll need to construct a PrintWriter
with the socket OutputStream
(or some other common object) as the lock.
Secondly, we have buffering within PrintWriter
. So come the end of a buffer, half get written and half wait for the next write. To prevent that, either externally lock to combine a print
and flush
, or use auto-flushing and add a new line character.
So, it isn't meaningfully thread-safe, but you can hack it. Or you can use a better design.
You need a way to use the same PrintWriter
between the threads (t1.writer == t2.writer
, not just PrintWriter
s created from the same OutputStream
). With the same PrintWriter
, all writing operations are synchronized.