Singleton class with updated parameters in java -
Singleton class with updated parameters in java -
public class threadsafesingleton implements serializable { @override public string tostring() { homecoming "threadsafesingleton [i=" + + ", str=" + str + "]"; } int i; string str; private static threadsafesingleton instance; public int geti() { homecoming i; } public void seti(int i) { this.i = i; } public string getstr() { homecoming str; } public void setstr(string str) { this.str = str; } private threadsafesingleton(){ } public static synchronized threadsafesingleton getinstance(int i,string str){ if(instance == null){ synchronized (threadsafesingleton.class) { if(instance == null){ instance = new threadsafesingleton(); } } } instance.seti(i); instance.setstr(str); homecoming instance; } public object readresolve(){ system.out.println("readresolve executed"); homecoming getinstance(this.i,this.str); } public static void main(string[] args) throws ioexception, exception { fileoutputstream fos = new fileoutputstream( "b://serilization//text1.txt"); objectoutputstream oos = new objectoutputstream(fos); threadsafesingleton obj = new threadsafesingleton(); obj.seti(1); obj.setstr("katrina kaif"); oos.writeobject(obj); system.out.println("serilization done"); fileinputstream fis = new fileinputstream("b://serilization//text1.txt"); objectinputstream ois = new objectinputstream(fis); threadsafesingleton copy=(threadsafesingleton) ois.readobject(); system.out.println("copy "+copy); system.out.println("deserilization done"); } }
in above code have singleton class containing int , string str attributes , have implemented serializable interface requirement when serialized class serialize class attributes values on 1 jvm , when deserialize on jvm should same instance of singleton class attributes in class should updated values provided during serialization
here on net checked solution got utilize readresolve method there can write logic set values of attributes provided during serialization of singleton class if see code of readresolve have written code "return getinstance(this.i,this.str);" here have used "this" keyword means current object beingness used hence have question have uncertainty code creating new object here "this" refers current object apart object created in getinstance(int i,string str) method can please explain breaking singleton ?
you may want read on java serialization: readobject() vs. readresolve(). when readresolve()
called, object has been deserialized stream , created. this
pointer, in case, object deserialization process has constructed, finish i
, str
values stream. if utilize this.i
, this.str
build new singleton, you're not creating new object new jvm's specific parameters.
class singleton
Comments
Post a Comment