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!
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 ObjectOutputStream
s concurrently.
OutputStream
s from java.nio.file.Files.newOutputStream​
are thread-safe but that is not automatically conferred to "decorators".
Writer
s have some explicit locking, but makes an absolute pigs ear of it.