digital_infinity
digital_infinity

Reputation: 564

Do I need to synchronize writeObject()?

I have some objects which are accessed concurrently by RMI serialization. Recently I had written custom serialization methods:

/** This method is made to omit serialization of this.order */
private void writeObject(java.io.ObjectOutputStream out)
  throws java.io.IOException
{
    Order tmpOrder = this.order;
    this.order = null;
    out.defaultWriteObject();
    this.order = tmpOrder;
}

private void readObject(java.io.ObjectInputStream in)
  throws java.io.IOException, ClassNotFoundException
{
    in.defaultReadObject();
}

I don't want to permit to spoil this.order by concurrent RMI thread.

  1. Do I need to make writeObject synchronized ? or
  2. Does the RMI framework do all the best to synchronize the access to the object ?

In second case my synchronization could even cause deadlocks in RMI. The general contract of JAVA API is that a method is called by one thread except noted specifically. So if I should follow the rule I should leave the writeObject w/o any synchronization. Is this correct ?

Another solution to my problem without answering the question is certainly declaring private static final ObjectStreamField[] serialPersistentFields. (I cannot make a field transient because the object is not only a DTO but an JPA Entity also)

Upvotes: 0

Views: 2013

Answers (2)

user207421
user207421

Reputation: 311031

I have some objects which are accessed concurrently by RMI serialization

No you don't. You have some objects that are accessed concurrently by Object Serialization.

Does the RMI framework do all the best to synchronize the access to the object?

No. The Object Serialization framework might, but it isn't specified.

Upvotes: 2

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147164

Attempting to serialise objects that are being used concurrently is going to lead to a mess. Certainly to read a consistent state or even a well-formed state you will generally need exclusive locking. If writeObject is syncrhonised, then you have extreme problems making sure the lock-ordering is well behaved.

Adding serialPersistentFields (spelt correctly:) should have the same behaviour as making fields transient. Making order transient will stop it being written out, which seems to be what you are attempting in the question code. Using ObjectOutputStream.putFields can also achieve something similar.

Upvotes: 1

Related Questions