[concurrency-interest] Concurrent Serialization Pattern
Thomas Hawtin
tackline at tackline.plus.com
Thu Sep 14 14:23:12 EDT 2006
Kevin Condon wrote:
>
> And viola! There's the pattern. I'd summarize the principles this way:
>
> 1. Make locks immutable fields, using the final modifier and rely on
> the default serialization handling to create the necessary
> happens-before relationships for lock field value visibility. (See
> JLS 17.5.3.)
>
> 2. Use a custom serialization form (see Effective Java, Item 55) and
> make sure to create happens-before relationships on all
> serialized/deserialized fields by using the same locking required for
> ordinary run-time access.
In 1.6, java.util.Random (resetSeed method) uses sun.misc.Unsafe to poke
it's final, (effectively) transient seed field. Not something I would
generally recommend.
If you don't have to worry about a serialisable base class, then it
might be simpler just to introduce a non-serialisable, package private
base class.
abstract class SerialBase { // Must not implement Serializable
final ReadWriteLock lock = new ReentrantReadWriteLock();
SerialBase() {
}
}
public class Serial extends SerialBase implements Serializable {
private static final long serialVersionUID = 2006091401L;
private int x;
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();
}
}
}
Tom Hawtin
More information about the Concurrency-interest
mailing list