java - transient for serializing singleton -
effective java - maintain singleton guarantee, have declare instance fields transient , provide 'readresolve' method. achieve declaring fields transient here? here's 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 " + c.getstate()); } catch (exception e) { e.printstacktrace(); } } }
irrespective of whether declare 'state' variable transient or not ,i c.getstate() gettign printed out 25. missing here?
what gain making attribute transient don't serialize state. serializing unnecessary, since it's discarded anyway readresolve() method.
if state consists in int, doesn't matter much. if state complex graph of objects, makes significant performance difference. , of course, if state not serializable, don't have other choice.
that said, serializing singleton questionable.
Comments
Post a Comment