Java. Serialization of objects in a multithreaded environment

徘徊边缘 提交于 2019-11-29 15:11:07
  • Is serialization safe in this case?

No. As @Tom Hawtin says, you will need to perform your own locking to ensure that the object(s) are not changed while you are serializing them.

  • How does it work under the hood? That is to say, will the ObjectOutputStream performing the serialization block until no threads are any longer operating on Counter?

ObjectOutputStream does no locking under the hood. It is up to the application to do this, if it is necessary.

  • What if Counter's synchronization doesn't use the intrinsic lock, but some other lock?

Then your application will also need to use that other lock to lock out updates while serialization is happening.

If the state that you are serializing simply consists of the state of one object with two fields, then lock contention and granularity should not be a problem. But if the object(s) are complicated, then lock contention could well be problematic, as could the problem of acquiring the locks without risking deadlock. That scenario would require careful design.

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!