码迷,mamicode.com
首页 > 其他好文 > 详细

Serialization: Understand 'readResolve'

时间:2014-08-23 13:54:40      阅读:247      评论:0      收藏:0      [点我收藏+]

标签:des   style   color   java   os   io   strong   for   ar   

What are the writeReplace() and readResolve() methods used for?

These methods are used to allow an object to provide an alternative representation for itself within an ObjectStream. Consider for instance the common means of implementing an enumerated type:

public class Gender implements Serializable {
  public final static Gender MALE   = new Gender("Male");
  public final static Gender FEMALE = new Gender("Female");

  private String name;

  private Gender(String name) {
    this.name = name;
  }
}
This works fine within one JVM; there will be at most two Gender objects created, no matter how often you use Gender.MALE and Gender.FEMALE in your code. However, consider what happens when an instance of this class is serialized across JVMs. The ObjectInputStream will create a new instance of Gender that has the same value as the original instance. So, if you have many thousands objects that have been de-serialized via RMI you might end up with many thousands of extra instances of Gender. The writeReplace() and readResolve() methods are the hook to solve this problem.

 

One way of eliminating the extra instances and some of the unnecessary heap allocation would be to do something like this:

public class Gender implements Serializable {
  public final static Gender MALE   = new Gender("Male");
  public final static Gender FEMALE = new Gender("Female");

  private String name;

  private Gender(String name) {
    this.name = name;
  }

  Object writeReplace() throws ObjectStreamException {
    if (this.equals(MALE)) {
      return SerializedForm.MALE_FORM;
    } else {
      return SerializedForm.FEMALE_FORM;
    }
  }

  private static class SerializedForm implements Serializable {

    final static SerializedForm MALE_FORM   = new SerializedForm(0);
    final static SerializedForm FEMALE_FORM = new SerializedForm(1);

    private int value;

    SerializedForm(int value) {
      this.value = value;
    }

    Object readResolve() throws ObjectStreamException {
      if (value == MALE_FORM.value) {
        return Gender.MALE;
      } else {
        return Gender.FEMALE;
      }
    }
  }
}
This also guarantees that in all cases where genderInstance.equals(MALE) is true,genderInstance == Gender.MALE is also true.
 
 
 

Serialization is a handy and powerful aspect of Java. Being able to persist objects onto disk and read them later is one of the most under-used features of Java I think. In the base cases, serialization can ‘just work‘. However, as more complicated object formats and design patterns are adopted, the likelihood that ‘transparent‘ object serialization will ‘just work‘ becomes less and less likely. One case where serialization needs a little help is when dealing with a controlled set of instances - such as singletons and enumerations.

Whenever a singleton is serializable, it‘s important to ensure that the singleton instance is used. This is done through thereadResolve method. For instance, a singleton may look like this:

 

public final class MySingleton {
 private MySingleton() { }
 private static final MySingleton INSTANCE = new MySingleton();
 public static MySingleton getInstance() { return INSTANCE; }
}

 

In the above example, there is only one way to get an instance of MySingleton - that is to use the getInstance() method. Unfortunately, this code becomes ‘broken‘ simply by adding one interface implementation:

 

public final class MySingleton implements Serializable {
//...

 

Now through the serializable tools, someone can write a singleton instance to disk, and then read it back up, effectively getting a new instance. Even though the constructor is private, the serializable tools have special access to create instances of a class regardless. Serialization has a special hook it uses - a private method on the class being instantiated called readResolve() - which is meant to supply a ‘hook‘ for a class developer to ensure that they have a say in what object is returned by serialization. Oddly enough, readResolve() is not static, but is instead invoked on the new instance just created by the serialization. We‘ll get into that in a minute - for now, here is how our readResolve() method works with our singleton:

 

public final class MySingleton {
 private MySingleton() { }
 private static final MySingleton INSTANCE = new MySingleton();
 public static MySingleton getInstance() { return INSTANCE; }
 private Object readResolve() throws ObjectStreamException {
  // instead of the object we‘re on, 
  // return the class variable INSTANCE
  return INSTANCE; 
 }
}

 

So far so good. Things get a little complicated when dealing with more than one instance however. To explain this, I‘ll show this using a type-safe enumeration. Keep in mind that Java 5‘s enum type automatically handles this readResolve case for you. Here is a nice little enumeration:

 

public final class Sides {
 private int value;
 private Sides(int newVal) { value = newVal; }
 private static final int LEFT_VALUE = 1;
 private static final int RIGHT_VALUE = 2;
 private static final int TOP_VALUE = 3;
 private static final int BOTTOM_VALUE = 4;
 
 public static final LEFT = new Sides(LEFT_VALUE);
 public static final RIGHT = new Sides(RIGHT_VALUE);
 public static final TOP = new Sides(TOP_VALUE);
 public static final BOTTOM = new Sides(BOTTOM_VALUE);
 
}

 

Now, implementing serialization, the key to determining which instance to return is in inspecting what value is set on the object itself:

 

public final class Sides implements Serializable {
 private int value;
 private Sides(int newVal) { value = newVal; }
 private static final int LEFT_VALUE = 1;
 private static final int RIGHT_VALUE = 2;
 private static final int TOP_VALUE = 3;
 private static final int BOTTOM_VALUE = 4;
 
 public static final LEFT = new Sides(LEFT_VALUE);
 public static final RIGHT = new Sides(RIGHT_VALUE);
 public static final TOP = new Sides(TOP_VALUE);
 public static final BOTTOM = new Sides(BOTTOM_VALUE);
 
 private Object readResolve() throws ObjectStreamException {
  // Switch on this instance‘s value to figure out which class variable
  // this is meant to match
  switch(value) {
   case LEFT_VALUE: return LEFT;
   case RIGHT_VALUE: return RIGHT;
   case TOP_VALUE: return TOP;
   case BOTTOM_VALUE: return BOTTOM;  
  }
  return null;
 }
}

Serialization: Understand 'readResolve'

标签:des   style   color   java   os   io   strong   for   ar   

原文地址:http://www.cnblogs.com/hellotech/p/3930954.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!