Is PrintWriter thread-safe?

It's not exactly the same question and there's no evidence given.

It also says PrintWriter is thread-safe without the qualification whereas another answer had the qualification. In my view this needs clarification.

Since the OP doesn't understand (or maybe doesn't believe) the answers to the linked question, I will restate them.

  • The primary specification (i.e. the javadocs) do not state whether or not the class is thread-safe.

  • It is clear from reading the source code that it is thread-safe in the sense that all relevant operations are properly synchronized.

  • It is unlikely that Oracle would deliberately change the implementation to make it non-thread-safe ... in the sense above.

  • However, there are use-cases where a PrintWriter may not be completely thread-safe:

    • If a single PrinterWriter is used by multiple threads, the result can be unpredictable interleaving of output from the threads; e.g. if they use print rather than println.

    • If you have multiple PrintWriter objects wrapping the same underlying stream, there could be problems due to the PrintWriters internal use of a BufferedWriter.

    • Things may change if you subclass PrintWriter.

In summary, the current PrintWriter implementation (in the Oracle/OpenJDK codebase) is thread-safe, but you still need to be careful in some situations. There is also the possibility other 3rd-party Java implementations (i.e. not derived from the OpenJDK source tree) might not be thread-safe.

Thread-safety of applications that involve multiple threads writing to the same underlying stream is always nuanced ...


Note that the quote that @KazekageGaara found ...

"All of the methods of PrintWriter that write multiple times to the underlying output stream handle synchronization internally, so that PrintWriter objects are thread-safe."

... is from an O'Reilly text book - "Java Fundamental Classes Reference" by Mark Grand and Jonathan Knudsen. Since this is not an official Sun / Oracle publication, it is not in any way definitive.


This question does not have a simple answer...

The Writer, which is the superclass of PrintWriter explicitly mentions in its constructor documentation that all critical sections synchronize either on the Writer instance itself, or on an explicitly specified object. Therefore Writer is explicitly thread-safe...

Unfortunately, the PrintWriter subclass documentation makes no such promises explicitly. It inherits the Writer lock object, but there is no way to know whether any additional or overridden methods are still thread-safe.

On the other hand, as far as I can tell the Sun/OpenJDK PrintWriter implementation contains synchronized blocks in pretty much every method. But this does not seem to be explicitly documented behavior.

I'd rather play it safe and assume that PrintWriter is not thread-safe, than rely on undocumented behavior and regret this in the long run...