Most Read This Week
Secrets of Java Serialization
Secrets of Java Serialization
By: Gene Callahan
Nov. 1, 2000 12:00 AM
Serialization in Java is an operation in which an object's internal state is translated into a stream of bytes. This binary stream or image of the object is created in an operating system-neutral network byte order. The image can be written to a disk, stored in memory, or sent over a network to a different operating system. This amazing feat requires little or no work on the part of the programmer. Just implement the serializable interface, which contains no methods, and call the writeObject() method on your object, and it's serialized! You can serialize an object to or from any I/O device that Java supports.
The serializable interface doesn't contain any code or data; it's a marker interface. If a hierarchy of classes is to be serialized, each class in the hierarchy must implement the serializable interface. All objects that are in an object hierarchy, or "Web of objects," at runtime will be serialized. If any one of them doesn't implement serializable, an exception will be thrown.
Serialization works across platforms - an object serialized on Solaris can be read on Windows. This is a key component in making Java's write once, run anywhere philosophy real, as well as the core requirement that Java programs be able to effectively and easily communicate with each other.
The default serialization capabilities often do the job. When that's not the case, Java allows progressive customization of the process at the class level. A class can contain its own readObject() and writeObject() methods to add data to the stream, set variables to special values, and more. We've found that we use readObject() frequently to reinitialize fields that it doesn't make sense to serialize, such as a database connection handle. We use writeObject() a lot less.
For those who really need a custom solution, Java provides the externalizable interface, which allows (in fact, forces) the class that implements it to take complete control of reading and writing instances of itself to the I/O stream. In over a year of using serialization every day, we've never had to resort to this level of customization. Still, it's nice to know that it's there.
What Are Some Uses for Serialization?
Just send the common objects back and forth and you're done. Designing messaging protocols is notoriously finicky. Once again Java saves the day and makes a previously arduous task a simple matter of a single method call.
Serialization over networks is the basis of Sun's communications infrastructure: RMI uses it, as well as the many communications subsystems in Jini such as JNDI.
Another use of serialization is to store complete objects as BLOBs in a relational database. This can provide a way to use traditional databases with an object-oriented programming language without needing to move to a true object-oriented database.
Tips and Traps
Trap 2: Versioning
You can take over version stamp creation yourself, but watch carefully for versions that really aren't compatible (such as the addition or deletion of a new class member). If you do want to take control of versioning of a class yourself, you must declare the following in the class's source code:
Static final long serialVersionUID = 12; // 12 is just an example!
Whenever you make changes that would prevent compatible serialization, bump up the version number.
Rather than trying to keep track of this ourselves, we let Java do the work for us through the class java.io.ObjectStreamClass. We prevent the "incompatible version" problem by sharing JAR files between programs that send serialized objects back and forth. The common JAR files contain all the shared classes. This prevents two different programs from trying to use different versions of the same class.
Sun also changes the serialization format occasionally. This is something to watch for if you're generating a serialized object store with some persistence, for instance, a disk cache that will remain around for some time. Fortunately, Sun seems intent on incorporating ways to work around the problem when it does make these changes. Sun posted the following on the Java Web site (www.java.sun.com/) with the release of version 1.2:
It was necessary to make a change to the serialization stream format in JDKTM 1.2 that isn't backwards compatible to all minor releases of JDKTM.
1.1. To provide for cases where backwards [sic] compatibility is required, a capability has been added to indicate what PROTOCOL_VERSION to use when writing a serialization stream. The method ObjectOutputStream.useProtocolVersion takes as a parameter the protocol version to use to write the serialization stream.
Tip 1: Handling Static Variables
For static variables that are initialized when declared, serialization doesn't present any special problems. The first time the class is used, the variable in question will be set to the correct value.
Some statics can't be initialized this way. They may, for instance, be set by a human during the running time of the program. Let's say we have a static variable that turns on debugging output in a class. This variable can be set on a server by sending it some message, perhaps from a monitor program. We'll also imagine that when the server gets this message, the operator wants debugging turned on in all subsequent uses of the class in the clients that are connected to that server.
The programmer is now faced with a difficulty. When the class in question arrives at the client, the static variable's value doesn't come with it. However, it contains the default static state that's set when the class's no-argument constructor is called by writeObject(). How can the client programs receive the new correct value?
The programmer could create another message type and transmit that to the client; however, this requires a proliferation of message types, marring the simplicity that the use of serialization can achieve in messaging. The solution we've come up with is for the class that needs the static transmitted to include a "static transporter" inner class. This class knows about all the static variables in its outer class that must be set. It contains a member variable for each static variable that must be serialized. StaticTransporter copies the statics into its member variables in the writeObject() method of the class. The readObject() method "unwraps" this bundle and transmits the server's settings for the static variables to the client. Since it's an inner class, it'll be able to write to the outer class's static variables, regardless of the level of privacy with which they were declared.
Tip 2: Easy Cloning
In a deep copy the new object will get new copies of its data members, not just new pointers to the same data members. Most of the time when you want this behavior, you want it recursively so that the members' members are deep copied as well. A major problem with clone methods is the difficult code that's required for all the deep copying a class might require. To solve this problem we wrote a class called Cloner that removed the need to write clone methods at all. Cloner is small enough so it can be included here in its entirety:
ObjectInputStream in = new ObjectInputStream(bi);
Object no = in.readObject();
ByteArrayInputStream(b.toByteArray()); ObjectInputStream in = new ObjectInputStream(bi); Object no = in.readObject(); return no; } }
To use this class is easy:
Foo foo = new Foo();
Now "bar" is a completely new deep copy of Foo!
As Bruce Eckel points out in his excellent book Thinking in Java, it's an order of magnitude slower to clone this way. However, in situations where you need to do a deep copy and are more worried about development time than running time, this is a good alternative. And since objects aren't cloneable by default, you need access to their source to make them so. You can subclass an object just to make it serializable, but this only works if you're the one constructing it. If you need to deep copy a Web of objects, some of which are created inside libraries that you don't have the source for, serialization may be your only alternative.
Tip 3: Transient
For example, perhaps you store some objects in a linked list, but also keep them in a hashtable for quick lookup by value. Since the hashtable can easily be re-created from the list, you can mark it as transient. If the table is large, re-creating it can be much faster than serializing, transmitting, and deserializing it.
The use of transient can also be important for security considerations. If a class contains data members that hold information that shouldn't be made public, such as a clear text version of a password or employees' salaries, a malicious program might be able to read them from the serialized byte stream. Declaring those members transient will prevent them from ever being written to serialized output. (Java also allows for the encryption of byte streams if further security measures are needed.)
Reader Feedback: Page 1 of 1
Subscribe to the World's Most Powerful Newsletters
Today's Top Reads