Java Serialization Code Examples

Java Serialization Code Examples

Evolving Classes when three are three machines invloved A <---> B <---> C

When java deserialize object, any field of the object that does not appear in the stream is set to its default value. Values that appear in the stream, but not in the object, are discarded.

This works fine in most cases.

But how about there are three machines when serialize and deserialize?

For example, we have a class User, and first in machine A we serialize it and transfer it to machine B, in machine B, we deserialize it and do do some operations then serialize it and transfer it to machine C. in machine C, we deserialize it and do whatever we want.

We will also need to return the object back, C to B, then to A.

A(User) <---> B(User) <---> C(User)


Now, we have to add some new fields - for instance property age - to the Class User.

Imagine that the class version on A is latest, on B old version, on C is newest.

On B, when it deserialize User, and it would discard age property in the stream, then B deserialize it and transfer to C, there would be no field age, so on machine C, Java set age field to default value 0.


In this process, the age value is missing due to the old version on B.


One solution to this problem is to save all fields of the logical state of the

object User in a map, then writeObject writes this map to ObjectOutputStream, readObject get every field value from this map.

public class User implements Serializable {

     private static final long serialVersionUID = 1L;

     private Map fieldsMap = new HashMap();

     private void writeObject(ObjectOutputStream out) throws IOException {

         fieldsMap.put("firstName", firstName);

         fieldsMap.put("age", age);

         out.writeUnshared(fieldsMap);

     }

     private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {

         fieldsMap = (HashMap) in.readObject();

         firstName = (String) fieldsMap.remove("firstName");

         age = (Integer) fieldsMap.remove("age");

     }

}


Then if in B, its class definition doesn't include property age, its class looks like below:

public class User implements Serializable {

     private Map fieldsMap = new HashMap();

     private void writeObject(ObjectOutputStream out) throws IOException {

         fieldsMap.put("firstName", firstName);

         out.writeUnshared(fieldsMap);

     }

     private void readObject(ObjectInputStream in) throws IOException,ClassNotFoundException {

         fieldsMap = (HashMap) in.readObject();

         firstName = (String) fieldsMap.remove("firstName");

     }

}


Then in B, it doesn't modify age property in fieldsMap, so when deserialize this object,age property is still in fieldsMap, thus C can restore the original age value.


Changing type of an instance field

For example, we have a Class Inventory:

public class Inventory implements Serializable {

     private static final long serialVersionUID = 1L;

     private String name;

     private int amount;

}

Now we have to promote amount field from int to long in Class Inventory,

and meanwhile we need to ensure class compatibility, that is we must guarantee the new version

of class can deserialize an object saved by the earlier version of the class, and vice verse.


If we simply convert the int type to long, then when use the new version of class to deserialize an object saved by the earlier version, or vice verse, it would throw the following exception:

java.io.InvalidClassException: io.Inventory; incompatible types for field amount


We can use serialPersistentFields, readObject, writeObject to maintain backward compatibility with the serialization format.

public class Inventory implements Serializable {
    private static final long serialVersionUID = 1L;
    private String name;
    private long longAmount;
    private static final ObjectStreamField[] serialPersistentFields = {
            new ObjectStreamField("name", String.class),

            new ObjectStreamField("amount", int.class),
            new ObjectStreamField("longAmount", long.class), };
    private void writeObject(ObjectOutputStream out) throws IOException {
        ObjectOutputStream.PutField fields = out.putFields();
        fields.put("name", name);
        int intAmount;
        if (longAmount > Integer.MAX_VALUE)
            intAmount = Integer.MAX_VALUE;
        else
            intAmount = (int) longAmount;
        // or for short
         // intAmount = (int) ((longAmount > Integer.MAX_VALUE)? Integer.MAX_VALUE:longAmount);
        // For compatibility reason, we need to put the old values first.
        fields.put("amount", intAmount);
        fields.put("longAmount", longAmount);
        out.writeFields();
    }
    private void readObject(ObjectInputStream in) throws IOException,
            ClassNotFoundException {
        ObjectInputStream.GetField fields = in.readFields();
        name = (String) fields.get("name", "");
        // it there is no longAmount in the stream, then it is serialized by
        // older version, and use the int type amount
        if (fields.defaulted("longAmount")) {
            longAmount = fields.get("amount", (int) 0);
        } else {
            // long type - longAmount exists in this stream
            // the "(long)0" is a must, it tells java to read a field
            // named longAmount with a value of type long
            longAmount = fields.get("longAmount", (long) 0);
        }
        // or for short
        // longAmount = fields.defaulted("longAmount") ?
        //       fields.get("amount",(int) 0) : fields.get("longAmount", (long) 0);
    }

We have to run various kinds of tests to ensure class compatibility, first guarantee serialize and deserialize works when in same version, and then serialize an instance in the new release and deserialize it in old releases, and vice versa.


Distinguish default value from no-such-field case
    After add a field to existing class, when deserialize, we need to distinguish the case the response object doesn't include this field at all from that the field has default value.
    In the new class, directly setting the field to invalid value would not work, as when deserialize, If the stream doesn't include one field, Java would directly set the object to its default value, object to null, int to 0, etc.

public class User implements Serializable {
    private static final long serialVersionUID = 1L;
    private String firstName;
    // age field is added later, and need to distinguish its default value 0 from case response doesn't include this field
    // directly assigning age -1 would not work, when deserialize,
    // the stream doesn't include one field, Java would set the object to its default value, object to null, int to 0, etc.
    private int age;
    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
        ObjectInputStream.GetField fields = in.readFields();
        firstName = (String) fields.get("firstName","");
        age = fields.defaulted("age") ?
                -1 : fields.get("age", (int) 0);
    }
    // we still need rewrite writeObject
    private void writeObject(ObjectOutputStream out) throws IOException {
        out.defaultWriteObject();
    }

}

Miscs

public class SerializationUtils {
    public static Object deserialize(String filename)
            throws FileNotFoundException, IOException, ClassNotFoundException {
        Object object = null;
        FileInputStream fis = null;
        ObjectInputStream in = null;
        fis = new FileInputStream(filename);
        in = new ObjectInputStream(fis);
        object =  in.readObject();
        in.close();
        return object;
    }
    public static void serialize(String filename, Object object)
            throws FileNotFoundException, IOException {
        FileOutputStream fos = null;
        ObjectOutputStream out = null;
        fos = new FileOutputStream(filename);
        out = new ObjectOutputStream(fos);
        out.writeObject(object);
        out.flush();
        out.close();
    }
}

Read/Write object with ByteArrayInputStream/ByteArrayOutputStream

ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream oout = new ObjectOutputStream(bout);
oout.writeInt(20);
oout.flush();

byte[] bytes = bout.toByteArray();
ByteArrayInputStream bin = new ByteArrayInputStream(bytes);
ObjectInputStream oin = new ObjectInputStream(bin);
System.out.println(oin.readInt());


Resources:

Java I/O 2nd edition - Chapter 13. Object Serialization

Effective Java (2nd Edition) - Chapter 11 Serialization

Java Object Serialization Specification


Post a Comment

Labels

Java (159) Lucene-Solr (110) All (60) Interview (59) J2SE (53) Algorithm (37) Eclipse (35) Soft Skills (35) Code Example (31) Linux (26) JavaScript (23) Spring (22) Windows (22) Web Development (20) Tools (19) Nutch2 (18) Bugs (17) Debug (15) Defects (14) Text Mining (14) J2EE (13) Network (13) PowerShell (11) Chrome (9) Continuous Integration (9) How to (9) Learning code (9) Performance (9) UIMA (9) html (9) Design (8) Dynamic Languages (8) Http Client (8) Maven (8) Security (8) Trouble Shooting (8) bat (8) blogger (8) Big Data (7) Google (7) Guava (7) JSON (7) Problem Solving (7) ANT (6) Coding Skills (6) Database (6) Scala (6) Shell (6) css (6) Algorithm Series (5) Cache (5) IDE (5) Lesson Learned (5) Miscs (5) Programmer Skills (5) System Design (5) Tips (5) adsense (5) xml (5) AIX (4) Code Quality (4) GAE (4) Git (4) Good Programming Practices (4) Jackson (4) Memory Usage (4) OpenNLP (4) Project Managment (4) Python (4) Spark (4) Testing (4) ads (4) regular-expression (4) Android (3) Apache Spark (3) Become a Better You (3) Concurrency (3) Eclipse RCP (3) English (3) Firefox (3) Happy Hacking (3) IBM (3) J2SE Knowledge Series (3) JAX-RS (3) Jetty (3) Restful Web Service (3) Script (3) regex (3) seo (3) .Net (2) Android Studio (2) Apache (2) Apache Procrun (2) Architecture (2) Batch (2) Build (2) Building Scalable Web Sites (2) C# (2) C/C++ (2) CSV (2) Career (2) Cassandra (2) Distributed (2) Fiddler (2) Google Drive (2) Gson (2) Html Parser (2) Http (2) Image Tools (2) JQuery (2) Jersey (2) LDAP (2) Life (2) Logging (2) Software Issues (2) Storage (2) Text Search (2) xml parser (2) AOP (1) Application Design (1) AspectJ (1) Bit Operation (1) Chrome DevTools (1) Cloud (1) Codility (1) Data Mining (1) Data Structure (1) ExceptionUtils (1) Exif (1) Feature Request (1) FindBugs (1) Greasemonkey (1) HTML5 (1) Httpd (1) I18N (1) IBM Java Thread Dump Analyzer (1) JDK Source Code (1) JDK8 (1) JMX (1) Lazy Developer (1) Mac (1) Machine Learning (1) Mobile (1) My Plan for 2010 (1) Netbeans (1) Notes (1) Operating System (1) Perl (1) Problems (1) Product Architecture (1) Programming Life (1) Quality (1) Redhat (1) Redis (1) Review (1) RxJava (1) Solutions logs (1) Team Management (1) Thread Dump Analyzer (1) Troubleshooting (1) Visualization (1) boilerpipe (1) htm (1) ongoing (1) procrun (1) rss (1)

Popular Posts