Effective Java - To maintain the singleton guarantee, you
have to declare all instance fields transient and provide a 'readResolve' method.
What do we achieve by declaring the fields transient here?
Here's a sample:
....
....
public final class MySingleton implements Serializable{
private int state;
private MySingleton() { state =15; }
private static final MySingleton INSTANCE = new MySingleton();
public static MySingleton getInstance() { return INSTANCE; }
public int getState(){return state;}
public void setState(int val){state=val;}
private Object readResolve() throws ObjectStreamException {
return INSTANCE;
}
public static void main(String[] args) {
MySingleton c = null;
try {
c=MySingleton.getInstance();
c.setState(25);
FileOutputStream fs = new FileOutputStream("testSer.ser");
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(c);
os.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
FileInputStream fis = new FileInputStream("testSer.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
c = (MySingleton) ois.readObject();
ois.close();
System.out.println("after deser: contained data is " + c.getState());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Irrespective of whether I declare the 'state' variable as transient or not ,I get c.getState() gettign printed out as 25.
Am I Missing something here?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…