Java. Serialization of objects in a multithreaded environment

后端 未结 3 807
萌比男神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:15

    It's not safe, but it is relatively easy to make it so:

    synchronized (counter) {
        out.writeObject(counter);
    }
    

    As you noticed, the object locked is arbitrary, so how would the serialisation mechnaism know how to obtain the relevant lock. Worse than that, the order of serialising and object graph is also quite arbitrary, so any attempt to lock would often lead to deadlocks. Even with the solution above, you are performing a complex operation within a lock, so be careful about deadlocks.

提交回复
热议问题