Locking Java object before serialization

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

class SerializeMe implements Serializable{

private Foo foo;
private Bar bar;

}

      

if the classes Foo

and do Bar

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

, is it not very possible that in a multithreaded environment the state of variables Foo

or Bar

might change while serialization is in progress?

How can I ensure that the overall state of the parent class SerializeMe

doesn't change during serialization?

Is the best way to just create a lock on the object you want to serialize?

+3


source to share


1 answer


Serialization is not thread safe.

You can

synchronize(object){
 serialize(object)
}

      

But if some other stream already has links to Foo or bar, they can change it.



If you need to change the serialization of the 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 of my head, so please check it out.

[EDIT] As noted by Peter Lowry, it is synchronized

+2


source







All Articles