是否可以为serializable类创建锁暂态? [英] Is it okay to to make the lock transient for a Serializable class?

查看:177
本文介绍了是否可以为serializable类创建锁暂态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个实现 Serializable 的类,并且通过类型<$ c $的 lock 对象保护这个类的不变量c> Object 。是否可以暂时使用,还是可以产生任何不必要的副作用?



代码:

  class MyClass implements Serializable {

private final transient lock = new Object();
....
}


解决方案

这很好,只要你在反序列化后重新创建对象,以便您可以在其上进行同步。



此外,您可能需要< a href =http://stackoverflow.com/questions/2968876/final-transient-fields-and-serialization>删除 final 修饰符。 / p>

这是决定这是否值得的麻烦。


I have a class that implements Serializable and I protect the invariant of this class via a lock object which is of type Object. Is it okay to make it transient or can it have any unwanted side effects?

Code :

class MyClass implements Serializable{

 private final transient lock = new Object();
  ....
}

解决方案

This is fine, as long as you recreate the object upon de-serialization so that you have something to synchronize on.

Also, you'll probably have to remove the final modifier.

It's up to you to decide whether this is worth the hassle.

这篇关于是否可以为serializable类创建锁暂态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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