This example demonstrates how to use the writeReplace/readResolve methods. The readResolve method resolves the object read from the stream before it is returned to the caller. The writeReplace method allows a Serializable class of an object to nominate its own replacement in the stream before the object is written.
This example creates a symbol class for which only one instance of each each symbol binding exists. The Symbol class defines the readResolve method. A symbol is created from outside using the symbollookup method. The symbollookup method finds and returns a symbol if one already and, if one does not already exist, creates one. This assures uniqueness within one VM. Then, when the readResolve method is called as the symbol is being read, a preexisting equivalent Symbol object is substituted from the hashtable to maintain the unique identity constraint, if such a symbol exists. If the symbol does not exist, the new symbol is added to the hashtable and returned. This assures uniqueness when dealing with more than one VM.