Improve Singleton holder example

This commit is contained in:
Ilkka Seppälä 2016-05-07 11:38:55 +03:00
parent 0ad9937881
commit 2ed3748c9b

View File

@ -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
* <p/>
* 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.
* <p>
* 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.
* <p>
* 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();
}
}