2

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!

baopdh
  • 25
  • 2
  • 5

3 Answers3

2

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.

Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305
1

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

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
  • 1
    If you have two or more threads writing to the **same stream**, synchronizing won't help with your design flaw. – Kayaman Apr 02 '20 at 15:42
  • 1
    @Kayaman I am using (at least trying to use) the term *synchronizing* more abstractly than its keyword Java definition. For instance, using a queue with just one writer thread to synchronize. – ControlAltDel Apr 03 '20 at 13:28
  • Alright then. It wasn't immediately clear and might give the impression that streams are a similarly sharable resource as let's say a collection, as long as it's thread-safe. – Kayaman Apr 03 '20 at 14:21
0

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.

Varun Maurya
  • 337
  • 4
  • 18