Java. Serialization of objects in a multithreaded environment

后端 未结 3 809
萌比男神i
萌比男神i 2020-12-21 01:54

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

3条回答
  •  感情败类
    2020-12-21 02:20

    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();
    }
    

提交回复
热议问题