Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Putting lock on Java object before serialization

If I have a straightforward Java object with two instance variables:

class SerializeMe implements Serializable{

private Foo foo;
private Bar bar;

}

if the Foo and Bar classes implement the Serializable interface I should be good to go. But my question is, if I am in the process of serializing this class SerializeMe, isn't it very possible that in a multi-threaded environment that the state of foo or bar variables might change while the serialization is taking place?

How can I ensure that the overall state of the parent class SerializeMe will not change during serialization?

Is the best way to simply create a lock on the object you wish to serialize?


1 Answers

Serialization is not thread safe.

You can

synchronize(object){
 serialize(object)
}

But if any other thread already has references to Foo or bar they can modify it.

If you need to modify the serialization of a class you need to implement void writeObject(ObjectOutputStream).

private synchronized void writeObject(ObjectOutputStream out) throws IOException {
  synchronized(foo){
    synchronized(bar){
      out.defaultWriteObject();
}
}
}

This is out my head so please test it.

[EDIT]As Peter Lawrey noted it is synchronized

like image 55
gfelisberto Avatar answered May 05 '26 05:05

gfelisberto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!