Is it possible to do a lock interrupt for the Serializable class?

I have a class that implements Serializable , and I protect the invariant of this class through a lock object that is of type Object . Can this be transient, or can it have any unwanted side effects?

The code:

 class MyClass implements Serializable{ private final transient lock = new Object(); .... } 
0
source share
2 answers

This is great if you recreate an object during de-serialization so that you have something to sync.

In addition, you may have to remove the final modifier .

It's up to you to decide if this is a hassle.

+2
source

An alternative is to use an empty array (even new Object[0] ). Empty arrays are serializable, while new Object() is not.

I'm used to doing:

 private final Object lock = new Object[0]; 
+5
source

Source: https://habr.com/ru/post/1299157/


All Articles