I have an object whose internal mutable state is being constantly updated by one or more threads. The object is synchronized, and the goal is to periodically save its state
Whenever it's necessary to modify the serialization of a class you have to implement the special private method void writeObject(ObjectOutputStream)
. The ObjectOutputStream
uses this method instead of the default algorithm then.
In your case you want the serialization to be synchronized with the object. So all you have to do is adding the synchronized
keyword to the method. You can still use the default implementation defaultWriteObject
:
private synchronized void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
}