Is it okay to to make the lock transient for a Serializable class?

萝らか妹 提交于 2019-12-12 05:28:04

问题


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

回答1:


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.




回答2:


An alternative is using an empty array (even new Object[0]) instead. Empty arrays are serializable whereas new Object() isn't.

I got used to doing:

private final Object lock = new Object[0];


来源:https://stackoverflow.com/questions/15638972/is-it-okay-to-to-make-the-lock-transient-for-a-serializable-class

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