javamultithreadingserializationconcurrencyobjectoutputstream

Is ObjectOutputStream.writeObject to a file thread safe?


I am working on an application that has to serialize objects to a file for use later. There are multiple threads calling method writeObject (for different objects, same file) concurrently. Is the method thread-safe? Do I have to synchronize the write operation in application code?

For example: Thread 1 serializes object A, Thread 2 serializes object B. If I didn't synchronize them, would A and B get mixed up with each other in the file? Thanks!


Solution

  • Firstly, Java Serialization is dangerous so it should be avoided.

    No, ObjectOutputStream is not thread-safe. The API doesn't seem to make any claim about that. You can also check the source code, where there is only thread-safety for security.

    It's not thread-hostile so you can write to two independent ObjectOutputStreams concurrently.

    OutputStreams from java.nio.file.Files.newOutputStream​ are thread-safe but that is not automatically conferred to "decorators".

    Writers have some explicit locking, but makes an absolute pigs ear of it.