- Is serialization safe in this case?
Not. As @Tom Hawtin says, you will need to do your own locking to ensure that objects (objects) will not be changed when they are serialized.
- How does it work under the hood? That is, will an ObjectOutputStream execute a serialization block until the threads no longer run on the counter?
ObjectOutputStream does not block under the hood. This is necessary for the application, if necessary.
- What if the counter synchronization does not use the built-in lock, but some other lock?
Then your application will also need to use this other lock to block updates when serialization occurs.
If the state you are serializing just consists of the state of one object with two fields, then blocking conflicts and granularity should not be a problem. But if the object is complex, then a blocking conflict can be problematic, like the problem of acquiring locks without risking a dead end. This scenario will require careful design.
source share