Skip to content

Commit 2ed3748

Browse files
committed
Improve Singleton holder example
1 parent 0ad9937 commit 2ed3748

File tree

1 file changed

+20
-17
lines changed

1 file changed

+20
-17
lines changed

singleton/src/main/java/com/iluwatar/singleton/InitializingOnDemandHolderIdiom.java

Lines changed: 20 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -22,35 +22,38 @@
2222
*/
2323
package com.iluwatar.singleton;
2424

25-
import java.io.Serializable;
26-
2725
/**
28-
* The Initialize-on-demand-holder idiom is a secure way of creating lazy initialized singleton
29-
* object in Java. refer to "The CERT Oracle Secure Coding Standard for Java" By Dhruv Mohindra,
30-
* Robert C. Seacord p.378
31-
* <p/>
32-
* Singleton objects usually are heavy to create and sometimes need to serialize them. This class
33-
* also shows how to preserve singleton in serialized version of singleton.
26+
* The Initialize-on-demand-holder idiom is a secure way of creating a lazy initialized singleton
27+
* object in Java.
28+
* <p>
29+
* The technique is is as lazy as possible and works in all known versions of Java. It takes advantage
30+
* of language guarantees about class initialization, and will therefore work correctly in all
31+
* Java-compliant compilers and virtual machines.
32+
* <p>
33+
* The inner class is referenced no earlier (and therefore loaded no earlier by the class loader) than
34+
* the moment that getInstance() is called. Thus, this solution is thread-safe without requiring special
35+
* language constructs (i.e. volatile or synchronized).
3436
*
35-
* @author mortezaadi@gmail.com
3637
*/
37-
public final class InitializingOnDemandHolderIdiom implements Serializable {
38-
39-
private static final long serialVersionUID = 1L;
38+
public final class InitializingOnDemandHolderIdiom {
4039

40+
/**
41+
* Private constructor.
42+
*/
4143
private InitializingOnDemandHolderIdiom() {}
4244

45+
/**
46+
* @return Singleton instance
47+
*/
4348
public static InitializingOnDemandHolderIdiom getInstance() {
4449
return HelperHolder.INSTANCE;
4550
}
4651

47-
protected Object readResolve() {
48-
return getInstance();
49-
}
50-
52+
/**
53+
* Provides the lazy-loaded Singleton instance.
54+
*/
5155
private static class HelperHolder {
5256
public static final InitializingOnDemandHolderIdiom INSTANCE =
5357
new InitializingOnDemandHolderIdiom();
5458
}
55-
5659
}

0 commit comments

Comments
 (0)