Re: implement writeObject how? serializable singleton how?



Tom Hawtin <usenet@xxxxxxxxxxxxxxxxx> writes:

Frank Fredstone wrote:

public class MySingleton implements Serializable {
static MySingleton singleton = new MySingleton();
^private final
private MySingleton() {
}
// This method is called immediately after an object of
this // class is deserialized.
// This method returns the singleton instance.
protected Object readResolve() {
^^^^^^^^^private
return singleton;
}
}

If I add code to the constructor, it executes during
deserialization, so that doesn't work for me.

It shouldn't do. readObject (or a call to
ObjectInputStream.defaultReadObject) takes the place of the
constructor. For this sort of class, it doesn't really matter what the
fields are set to as you are going to dump the deserialised object.

The constructor is called during deserialization, maybe because of the
assignment to the field singleton. If I put a print statement in the
constructor, it executes during deserialization. If I use the
supposedly redundant "transient static" the constructor is still
called during deserialization. If I use transient only the constructor
is called during deserialization. If I use static final, the
constructor is called during deserialization.

Is there someway to determine within a static initializer or
constructor that this object is being constructed and not being
deserialized? If there were I could execute code only during the one
construction of the object, and not again.

I was thinking that I could implement readObject/writeObject. But, how can
I implement writeObject? How do you represent the fields?

Keep the readResolve (only make it private) and make any instance
fields transient (there is no point serialising them).

There is no change. The constructor is still called during deserialization.

In the oreilly RMI book there is an example of a writeObject method,
but it doesn't explain how you are supposed to represent fields of the
object. I've looked around a bit and found nothing.

You aren't interested in the fields.

(take the bit about singletons being evil as read)

I did read that article, but I'm not sure how it applies to what I'm
trying to do.

For my purposes, the singleton means "cause a side-effect only
once". I'm trying to find a way to have that behavior survive
deserialization.

The field "singleton" was important because witthout
serialization/deserialization it represents the one and only instance
of the object.(and the one and only time that the constructor was
called).

Any scheme I can think of so far to indicate to the class that it is
being constructed rather than deserialized is executed during
deserializaion also, so I can't distinguish between the two.

What about readObject/writeObject. I think I could get around the
problem by implementing writeObject. How should a writeObject method
represent the state of an object?
.



Relevant Pages