[concurrency-interest] Concurrent Serialization Pattern

Peter Jones peter.jones at sun.com
Fri Sep 15 11:45:32 EDT 2006


>   private transient int x;  // emit using custom serialization
>   ...
> 
>   private void writeObject(ObjectOutputStream out) throws IOException {
>     out.defaultWriteObject();
>     lock.readLock().lock();
>     try {
>       out.writeInt(x);
>     } finally {
>       lock.readLock().unlock();
>     }
>   }
> 
>   private void readObject(ObjectInputStream in)
>       throws IOException, ClassNotFoundException {
>     in.defaultReadObject();
>     lock.writeLock().lock();
>     try {
>       x = in.readInt();
>     } finally {
>       lock.writeLock().unlock();
>     }
>   }

[snip]

> Any thoughts on this pattern?

I would probably move the invocations on the streams "out"/"in"
outside the lock/unlock, so that you're not holding the lock during a
potentially blocking I/O operation on an arbitrary stream (at least
for the writing case, when some other thread might want the lock).
(And then I think you would have blocks of code similar to what's in
getX/setX, which you might want to share in private methods.)

If you would rather not write "x" as custom serialized form data, you
could use the ObjectOutputStream.putFields/PutField/writeFields and
ObjectInputStream.readFields/GetField APIs to still write it as the
serializable field named "x"-- for what it's worth.

-- Peter


More information about the Concurrency-interest mailing list