问题
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