{"id":2148,"date":"2017-04-05T05:20:29","date_gmt":"2017-04-05T05:20:29","guid":{"rendered":"http:\/\/codethataint.com\/blog\/?p=2148"},"modified":"2017-04-08T16:01:22","modified_gmt":"2017-04-08T16:01:22","slug":"singleton-and-serialization","status":"publish","type":"post","link":"https:\/\/codethataint.com\/blog\/singleton-and-serialization\/","title":{"rendered":"Singleton and Serialization"},"content":{"rendered":"<p><strong>In which scenario we should serialize a singleton?<\/strong><br \/>\nImagine you have a long-running app and want to be able to shut it down and later continue at the point where it was shut down (e.g. in order to do hardware maintenance). If the app uses a singleton that is stateful, you&#8217;d have to be able to save and restore the sigleton&#8217;s state, which is most easily done by serializing it.<\/p>\n<p><strong>Is it possible to serialize a singleton object?<\/strong><br \/>\n<em>2 Methods<\/em><\/p>\n<ol>\n<li>By using ENUM : ENUM implements Serializable by Default<\/li>\n<li>By adding <strong>implements Serializable<\/strong> to class to make it serializable, and delaring all instance fields transient (to prevent a serialization attack) and provide a readResolve method.<\/li>\n<\/ol>\n<p><strong>readResolve() method in Singleton Class implementing Serialization<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\n.\r\n.\r\n\/\/ readResolve method to preserve singleton property\r\nprivate Object readResolve() {\r\n     \/\/ Return the one true Elvis and let the garbage collector\r\n     \/\/ take care of the Elvis impersonator.\r\n    return INSTANCE;\r\n}\r\n.\r\n.\r\n<\/pre>\n<p><strong>Why you need readResolve() Method<\/strong><br \/>\nThis method will be invoked when you will de-serialize the object. Inside this method, you must return the existing instance to ensure single instance application wide.<\/p>\n<p>The Way serialization works is as below<\/p>\n<blockquote><p>Serializes the Object Property -> Stores to Persistent Storage<br \/>\nFrom Persistent Storage -> Creates new Object and Sets Properties of Object<\/p><\/blockquote>\n<p><strong>The Object Before Serialization and after Serialization are not same. Only the Object Properties are same<\/strong><\/p>\n<p>Now lets take a simple Example where we serializes the PrintReport Class which has priority as one of its Object Variable.priority tells which should be given first preference while printing<\/p>\n<p><strong>PrintReport.java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npackage com.mugil.org;\r\n\r\nimport java.io.Serializable;\r\n\r\npublic class PrintReport implements Serializable {\r\n    private static PrintReport instance = null;\r\n\t \r\n    public static PrintReport getInstance() {\r\n        if (instance == null) {\r\n            instance = new PrintReport();\r\n        }\r\n        return instance;\r\n    }\r\n    \r\n    private transient int priority = 2;\r\n\r\n\tpublic int getPriority() {\r\n\t\treturn priority;\r\n\t}\r\n\t\r\n\tpublic void setPriority(int priority) {\r\n\t\tthis.priority = priority;\r\n\t}\r\n}\r\n<\/pre>\n<p>Now when the above singleton which implements serialization gets called as below<\/p>\n<p><strong>PrintMedicalReport.java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npackage com.mugil.org;\r\n\r\nimport java.io.FileInputStream;\r\nimport java.io.FileOutputStream;\r\nimport java.io.IOException;\r\nimport java.io.ObjectInput;\r\nimport java.io.ObjectInputStream;\r\nimport java.io.ObjectOutput;\r\nimport java.io.ObjectOutputStream;\r\n\r\npublic class PrintMedicalReport \r\n{\t\r\n\t static PrintReport instanceOne = PrintReport.getInstance();\r\n\t \r\n\t    public static void main(String&#x5B;] args) {\r\n\t        try {\r\n\t            \/\/ Serialize to a file\r\n\t            ObjectOutput out = new ObjectOutputStream(new FileOutputStream(\r\n\t                    &quot;filename.ser&quot;));\r\n\t            out.writeObject(instanceOne);\r\n\t            out.close();\r\n\t            \r\n\t            instanceOne.setPriority(1);\r\n\t            \r\n\t            \/\/ Serialize to a file\r\n\t            ObjectInput in = new ObjectInputStream(new FileInputStream(\r\n\t                    &quot;filename.ser&quot;));\r\n\t            PrintReport instanceTwo = (PrintReport) in.readObject();\r\n\t            in.close();\r\n\t \r\n\t            System.out.println(instanceOne.getPriority());\r\n\t            System.out.println(instanceTwo.getPriority());\r\n\t \r\n\t        } catch (IOException e) {\r\n\t            e.printStackTrace();\r\n\t        } catch (ClassNotFoundException e) {\r\n\t            e.printStackTrace();\r\n\t        }\r\n\t    }\r\n}\r\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<pre>\r\n1\r\n2\r\n<\/pre>\n<p>Note in the above code the <strong>instanceOne.setPriority(2);<\/strong> should have been called before <strong>out.writeObject(instanceOne)<\/strong>.But that is not the case since the example explains the Object are different before and after Serialization.Only Object Properties(Metadata) are stored during serialization not the actual object.<\/p>\n<p>You can see the Class Prints default Priority value in the output.<\/p>\n<p>Now in context to singleton we want to maintain exactly one Object exist before and after serialization. Not with two object with same set of attributes.To achieve this we add <strong>readResolve()<\/strong> Method.<\/p>\n<p><strong>PrintReport.java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npackage com.mugil.org;\r\n\r\nimport java.io.Serializable;\r\n\r\npublic class PrintReport implements Serializable {\r\n\tprivate volatile static PrintReport instance = null;\r\n\t \r\n    public static PrintReport getInstance() {\r\n        if (instance == null) {\r\n            instance = new PrintReport();\r\n        }\r\n        return instance;\r\n    }\r\n    \r\n    private int priority = 1;\r\n\r\n\tpublic int getPriority() {\r\n\t\treturn priority;\r\n\t}\r\n\t\r\n\tpublic void setPriority(int priority) {\r\n\t\tthis.priority = priority;\r\n\t}    \r\n\t     \r\n    protected Object readResolve() {\r\n        return instance;\r\n    }   \r\n}\r\n<\/pre>\n<p>Now when the PrintMedicalReport class gets executed the Output would be as below<\/p>\n<p><strong>Output<\/strong><\/p>\n<pre>\r\n1\r\n1\r\n<\/pre>\n<p>When you Serialize and Deserialize new file would be created and stored in disk every time.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" src=\"http:\/\/codethataint.com\/blog\/wp-content\/uploads\/2017\/04\/Serizl.png\" height=\"165\" width=\"294\"\/><\/p>\n<p>In the above image by changing the filename.ser text you can change the attribute of objects serialized. This is known as Serialization attack. To overcome this you must declare all instance fields as transient.<\/p>\n<p><a href=\"http:\/\/www.javalobby.org\/java\/forums\/t17491.html\">Reference 2<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>In which scenario we should serialize a singleton? Imagine you have a long-running app and want to be able to shut it down and later continue at the point where it was shut down (e.g. in order to do hardware maintenance). If the app uses a singleton that is stateful, you&#8217;d have to be able&hellip; <a href=\"https:\/\/codethataint.com\/blog\/singleton-and-serialization\/\">Continue reading <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[227],"tags":[],"class_list":["post-2148","post","type-post","status-publish","format-standard","hentry","category-singleton"],"_links":{"self":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts\/2148","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/comments?post=2148"}],"version-history":[{"count":16,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts\/2148\/revisions"}],"predecessor-version":[{"id":2170,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts\/2148\/revisions\/2170"}],"wp:attachment":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/media?parent=2148"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/categories?post=2148"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/tags?post=2148"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}