From 2ed3748c9bf0a6170cb07e647d7d758b4f6d6114 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ilkka=20Sepp=C3=A4l=C3=A4?= Date: Sat, 7 May 2016 11:38:55 +0300 Subject: [PATCH] Improve Singleton holder example --- .../InitializingOnDemandHolderIdiom.java | 37 ++++++++++--------- 1 file changed, 20 insertions(+), 17 deletions(-) diff --git a/singleton/src/main/java/com/iluwatar/singleton/InitializingOnDemandHolderIdiom.java b/singleton/src/main/java/com/iluwatar/singleton/InitializingOnDemandHolderIdiom.java index 84444ec2e..4aa6afe12 100644 --- a/singleton/src/main/java/com/iluwatar/singleton/InitializingOnDemandHolderIdiom.java +++ b/singleton/src/main/java/com/iluwatar/singleton/InitializingOnDemandHolderIdiom.java @@ -22,35 +22,38 @@ */ package com.iluwatar.singleton; -import java.io.Serializable; - /** - * The Initialize-on-demand-holder idiom is a secure way of creating lazy initialized singleton - * object in Java. refer to "The CERT Oracle Secure Coding Standard for Java" By Dhruv Mohindra, - * Robert C. Seacord p.378 - *

- * Singleton objects usually are heavy to create and sometimes need to serialize them. This class - * also shows how to preserve singleton in serialized version of singleton. + * The Initialize-on-demand-holder idiom is a secure way of creating a lazy initialized singleton + * object in Java. + *

+ * The technique is is as lazy as possible and works in all known versions of Java. It takes advantage + * of language guarantees about class initialization, and will therefore work correctly in all + * Java-compliant compilers and virtual machines. + *

+ * The inner class is referenced no earlier (and therefore loaded no earlier by the class loader) than + * the moment that getInstance() is called. Thus, this solution is thread-safe without requiring special + * language constructs (i.e. volatile or synchronized). * - * @author mortezaadi@gmail.com */ -public final class InitializingOnDemandHolderIdiom implements Serializable { - - private static final long serialVersionUID = 1L; +public final class InitializingOnDemandHolderIdiom { + /** + * Private constructor. + */ private InitializingOnDemandHolderIdiom() {} + /** + * @return Singleton instance + */ public static InitializingOnDemandHolderIdiom getInstance() { return HelperHolder.INSTANCE; } - protected Object readResolve() { - return getInstance(); - } - + /** + * Provides the lazy-loaded Singleton instance. + */ private static class HelperHolder { public static final InitializingOnDemandHolderIdiom INSTANCE = new InitializingOnDemandHolderIdiom(); } - }