Is ObjectOutputStream.writeObject to a file thread safe?

Viewed 563

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!

3 Answers

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.

It depends. If they are writing to the same file, then yes, this should be synchronized. But this is generally true even outside of object serialization: If you have two or more threads writing to the same stream, they need to be synchronized.

If they are each writing to their own streams/files, then you don't have resource conflict and it would be thread-safe

If multiple threads are writing to same file you have to synchronize the writing method as ObjectOutputStream is not threadsafe out of the box. You might end up with mixedup result and different kind of threading issues.

Related