[concurrency-interest] Concurrent Serialization Pattern

Kevin Condon conivek at gmail.com
Thu Sep 14 19:46:43 EDT 2006


Sorry, I just realized that there's a simpler solution.  Really just
need to make lock a transient final.  Then it doesn't have to be
serialized and you're not forced to use custom serialization if you
don't want to.  I didn't realize that the final sematics had
precedence over the transient qualifier, so I incorrectly thought that
lock would have the default null value after deserialization.

public class Serial implements Serializable {
 private static final long serialVersionUID = 2006091400L;
 private transient final ReentrantReadWriteLock lock =
    new ReentrantReadWriteLock();
 private int x;

 public int getX() {
   lock.readLock().lock();
   try {
     return x;
   } finally {
     lock.readLock().unlock();
   }
 }

 public void setX(int x) {
   lock.writeLock().lock();
   try {
     // imagine some long running op here ...
     this.x = x;
   } finally {
     lock.writeLock().unlock();
   }
 }

 private void writeObject(ObjectOutputStream out) throws IOException {
   lock.readLock().lock();
   try {
     out.defaultWriteObject();
   } finally {
     lock.readLock().unlock();
   }
 }

 private void readObject(ObjectInputStream in)
     throws IOException, ClassNotFoundException {
   lock.writeLock().lock();
   try {
     in.defaultReadObject();
   } finally {
     lock.writeLock().unlock();
   }
 }
}

Are there any problems with this simplified pattern?  Especially, is
there any risk of readObject() seeing the default null value for lock
and getting an NPE?  (I don't think there is, but that's at the heart
the whole concurrency puzzle thread.)  Are there other alternatives?

Regards,
Kevin


More information about the Concurrency-interest mailing list