Improve Singleton holder example
This commit is contained in:
parent
0ad9937881
commit
2ed3748c9b
@ -22,35 +22,38 @@
|
|||||||
*/
|
*/
|
||||||
package com.iluwatar.singleton;
|
package com.iluwatar.singleton;
|
||||||
|
|
||||||
import java.io.Serializable;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The Initialize-on-demand-holder idiom is a secure way of creating lazy initialized singleton
|
* The Initialize-on-demand-holder idiom is a secure way of creating a lazy initialized singleton
|
||||||
* object in Java. refer to "The CERT Oracle Secure Coding Standard for Java" By Dhruv Mohindra,
|
* object in Java.
|
||||||
* Robert C. Seacord p.378
|
* <p>
|
||||||
* <p/>
|
* The technique is is as lazy as possible and works in all known versions of Java. It takes advantage
|
||||||
* Singleton objects usually are heavy to create and sometimes need to serialize them. This class
|
* of language guarantees about class initialization, and will therefore work correctly in all
|
||||||
* also shows how to preserve singleton in serialized version of singleton.
|
* 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 {
|
public final class InitializingOnDemandHolderIdiom {
|
||||||
|
|
||||||
private static final long serialVersionUID = 1L;
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Private constructor.
|
||||||
|
*/
|
||||||
private InitializingOnDemandHolderIdiom() {}
|
private InitializingOnDemandHolderIdiom() {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return Singleton instance
|
||||||
|
*/
|
||||||
public static InitializingOnDemandHolderIdiom getInstance() {
|
public static InitializingOnDemandHolderIdiom getInstance() {
|
||||||
return HelperHolder.INSTANCE;
|
return HelperHolder.INSTANCE;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected Object readResolve() {
|
/**
|
||||||
return getInstance();
|
* Provides the lazy-loaded Singleton instance.
|
||||||
}
|
*/
|
||||||
|
|
||||||
private static class HelperHolder {
|
private static class HelperHolder {
|
||||||
public static final InitializingOnDemandHolderIdiom INSTANCE =
|
public static final InitializingOnDemandHolderIdiom INSTANCE =
|
||||||
new InitializingOnDemandHolderIdiom();
|
new InitializingOnDemandHolderIdiom();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user