Q:

Serialization of Java Objects

I'm trying to evaluate the usefulness of using Serialized objects in a Java application I'm developing.  I'm trying to determine if the following makes sense for an Object-serialization implementation, or if I should custom-build the transport.  Here's my scenario:

Objects will be transported over TCP from one application to another.
The serialized object will be an instance of a class stored in a common library.

Sample Class:
public class Room implements Serializable {
    // Instance Variables
    private Room roomWithinRoom;
    // ...
}

So my question is that since I will have several instance variables that reference back to the Room class, can I use Java serialization to accomplish the transfer of Room objects?  If I am able to accomplish this, will the pointers be preserved?  
Example:
Room mainRoom = new Room();
Room closet = new Room();
mainRoom.addRoom(closet);

If I send over the object "mainRoom," will it also serialize and send the "closet" instance (preserving the roomWithinRoom instance variable in mainRoom?)
Thanks a bunch, everyone!

A:

Yes, Java serialization does this really well.  Maybe too well.  I've had great luck writing to files.  With TCP be sure to call reset after each write.  Java will send a whole network graph in one go--your object, all the objects references, all they reference, and so on.  One writeObject can send gigabytes of data.  But without reset, if the next object you write was included in the first graph, all that will go across will be a reference to the previously sent object.  Any updated data will be ignored.  (Did I mention you should call reset after each writeObject?)
I'd suggest using the Externalizable interface.  This gives you a bit more control over what gets written.  (Actually, this is done on a class basis, so some classes can be Serializable and some Externalizable with no problem.)  This means you can write in the same format even when the class changes a bit.  It lets you skip data you don't need, and sometimes pass trivial objects as data primitives.  I also use version numbers so newer versions of the class can read stuff written by older versions.  (This is a bit more important when writing to files than with TCP.)  A warning:  when reading a class, be aware that the object reference you just read may not reference any data (that is, the referenced object has not be read in yet; you're looking at unitialized memory where the object's data will go.).
You'll probably fumble around with this a bit, but it does work really well once you understand it.

