Java的。在多线程环境中序列化对象 [英] Java. Serialization of objects in a multithreaded environment

查看:312
本文介绍了Java的。在多线程环境中序列化对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象,其内部可变状态由一个或多个线程不断更新。对象是同步的,目标是定期从另一个线程保存其状态(通过序列化):

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 (via serialization) from yet another thread:

public class Counter implements Serializable {
    private int dogCount;
    private int catCount;

    public synchronized void updateFromDogThread( int count ) { 
        dogCount = count; 
    }

    public synchronized void updateFromCatThread( int count ) { 
        catCount = count; 
    }
}

问题:


  • 在这种情况下序列化安全吗?

  • 它是如何工作的?也就是说, ObjectOutputStream 是否会执行序列化块,直到没有线程再次在 Counter 上运行?

  • 如果计数器的同步不使用内部锁,但是其他一些锁?

  • Is serialization safe in this case?
  • 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?
  • What if Counter's synchronization doesn't use the intrinsic lock, but some other lock?

推荐答案



  • 在这种情况下序列化安全吗?

否。正如@Tom Hawtin所说,你需要执行自己的锁定,以确保在序列化对象时不会更改对象。

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.



  • 它是如何在引擎盖下工作的?也就是说,ObjectOutputStream是否会执行序列化块直到没有线程再次在Counter上运行?

ObjectOutputStream 没有锁定。如果有必要,可以由应用程序来执行此操作。

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



  • 如果Counter的同步没有怎么办?使用内在锁,但其他一些锁?

那么你的应用程序也需要使用在序列化发生时锁定更新的其他锁定。

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.

这篇关于Java的。在多线程环境中序列化对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆