1
The Singleton pattern and implementations
Ming Yuan
October, 2013
10 questions?
1) Which classes are candidates of Singleton? Which kind of class do you make
Singleton in Java?
2) Can you write code for getInstance() method of a Singleton class in Java?
3) Is it better to make whole getInstance() method synchronized or just critical
section is enough? Which one you will prefer?
4) What is lazy and early loading of Singleton and how will you implement it?
5) Example of Singleton in standard JAVA Development Kit?
6) What is double checked locking in Singleton?
7) How do you prevent for creating another instance of Singleton using clone()
method?
8) How do you prevent for creating another instance of Singleton using
reflection?
9) How do you prevent for creating another instance of Singleton during
serialization?
10) When is Singleton not a Singleton in Java?
2
The Singleton design pattern
• Ensure a class only has one instance per ????
3
Why does such pattern exist?
• To provide a global point of access to it.
– CachingServiceFactory in the AIC Java framework
• To create single controller in a module
– CodesService and ComplexCodesService in the framework
4
Basic implementation elements in Java
• a class constructor with private access modifier
• a static variable to keep it sole instance
• a static method returning a reference to the instance, for
example getInstance()
5
01. public class SingletonPattern
02. {
03. private static SingletonPattern instance;
04.
05. private SingletonPattern()
06. {
07. }
08.
09. public static SingletonPattern getInstance()
10. {
11. return instance;
12. }
13. }
When should initialization happen?
• Eager initialization idiom – public field
6
01. public class SingletonPattern
02. {
03. public final static SingletonPattern instance =
new SingletonPattern();
04.
05. private SingletonPattern()
06. {
07. }
08.
09. }
When should initialization happen?
• Eager initialization idiom – private field
7
01. public class SingletonPattern
02. {
03. private static SingletonPattern instance = new SingletonPattern();
04.
05. private SingletonPattern()
06. {
07. }
08.
09. public static SingletonPattern getInstance()
10. {
11. return instance;
12. }
13. }
When should initialization happen?
• Lazy initialization idiom
8
01. public class SingletonPattern
02. {
03. private static SingletonPattern instance;
04.
05. private SingletonPattern()
06. {
07. }
08.
09. public synchronized static SingletonPattern getInstance()
10. {
11. if (instance == null)
12. {
13. instance = new SingletonPattern();
14. }
15. return instance;
16. }
17. }
When should initialization happen?
• Lazy initialization holder class idiom
9
01. public class SingletonPattern
02. {
03. private static class SingletonPatternHolder {
04. public static instance = new SingletonPattern();
05. }
06
07. private SingletonPattern()
08. {
09. }
10.
11. public static SingletonPattern getInstance()
12. {
13. return SingletonPatternHolder.instance;
14. }
15. }
When should initialization happen?
• Lazy initialization idiom with Java 5.0 – EBay way
10
public class Singleton {
private static Singleton instance;
private static ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
public static Singleton getInstance() {
lock.readLock().lock();
try {
if (instance == null) {
lock.readLock().unlock();
lock.writeLock().lock();
try {
if (instance == null) {
instance = new Singleton();
}
} finally {
lock.readLock().lock();
lock.writeLock().unlock();
}
}
return instance;
} finally {
lock.readLock().unlock();
}
}
private Singleton() {}
}
When should initialization happen?
• Double-checked locking (DCL) idiom
11
01. public class SingletonPattern
02. {
03. private volatile static SingletonPattern instance;
04.
05. private SingletonPattern()
06. {}
07.
08. public static SingletonPattern getInstance()
09. {
10. if (instance == null) {
11. synchronized (SingletonPattern.class) {
12. if (instance == null)
13. {
14. instance = new SingletonPattern();
15. }
16. }
17. }
18. return instance;
19. }
20. }
If Serializable is implemented
12
public class Singleton implements Serializable {
private static Singleton singleton = new Singleton();
private Singleton() {
}
// This method is called immediately after an object of
// this class is deserialized. This method returns the
// singleton instance.
protected Object readResolve() {
return singleton;
}
}
If Cloneable is implemented
13
public class Singleton implements Cloneable {
private static Singleton singleton = new Singleton();
private Singleton() {
}
public Object clone() throws CloneNotSupportedException
{
throw new CloneNotSupportedException();
}
}
You can break previous
implementations
• If using java.lang.reflect package,
• Or creating a custom ClassLoader
14
constructor.setAccessible (true);
Enum singleton – the best way
• Enum singleton doesn’t have protected/public constructors
• It implements serializable and comparable
• JVM ensures a single instance in multithreaded environment
• Does not allow invocation of private constructors through
reflection attacks
15
public enum SingletonEnum{
INSTANCE;
public void someMethod() {}
}
SingletonEnum.INSTANCE.someMethod();
References
16

Singleton

  • 1.
    1 The Singleton patternand implementations Ming Yuan October, 2013
  • 2.
    10 questions? 1) Whichclasses are candidates of Singleton? Which kind of class do you make Singleton in Java? 2) Can you write code for getInstance() method of a Singleton class in Java? 3) Is it better to make whole getInstance() method synchronized or just critical section is enough? Which one you will prefer? 4) What is lazy and early loading of Singleton and how will you implement it? 5) Example of Singleton in standard JAVA Development Kit? 6) What is double checked locking in Singleton? 7) How do you prevent for creating another instance of Singleton using clone() method? 8) How do you prevent for creating another instance of Singleton using reflection? 9) How do you prevent for creating another instance of Singleton during serialization? 10) When is Singleton not a Singleton in Java? 2
  • 3.
    The Singleton designpattern • Ensure a class only has one instance per ???? 3
  • 4.
    Why does suchpattern exist? • To provide a global point of access to it. – CachingServiceFactory in the AIC Java framework • To create single controller in a module – CodesService and ComplexCodesService in the framework 4
  • 5.
    Basic implementation elementsin Java • a class constructor with private access modifier • a static variable to keep it sole instance • a static method returning a reference to the instance, for example getInstance() 5 01. public class SingletonPattern 02. { 03. private static SingletonPattern instance; 04. 05. private SingletonPattern() 06. { 07. } 08. 09. public static SingletonPattern getInstance() 10. { 11. return instance; 12. } 13. }
  • 6.
    When should initializationhappen? • Eager initialization idiom – public field 6 01. public class SingletonPattern 02. { 03. public final static SingletonPattern instance = new SingletonPattern(); 04. 05. private SingletonPattern() 06. { 07. } 08. 09. }
  • 7.
    When should initializationhappen? • Eager initialization idiom – private field 7 01. public class SingletonPattern 02. { 03. private static SingletonPattern instance = new SingletonPattern(); 04. 05. private SingletonPattern() 06. { 07. } 08. 09. public static SingletonPattern getInstance() 10. { 11. return instance; 12. } 13. }
  • 8.
    When should initializationhappen? • Lazy initialization idiom 8 01. public class SingletonPattern 02. { 03. private static SingletonPattern instance; 04. 05. private SingletonPattern() 06. { 07. } 08. 09. public synchronized static SingletonPattern getInstance() 10. { 11. if (instance == null) 12. { 13. instance = new SingletonPattern(); 14. } 15. return instance; 16. } 17. }
  • 9.
    When should initializationhappen? • Lazy initialization holder class idiom 9 01. public class SingletonPattern 02. { 03. private static class SingletonPatternHolder { 04. public static instance = new SingletonPattern(); 05. } 06 07. private SingletonPattern() 08. { 09. } 10. 11. public static SingletonPattern getInstance() 12. { 13. return SingletonPatternHolder.instance; 14. } 15. }
  • 10.
    When should initializationhappen? • Lazy initialization idiom with Java 5.0 – EBay way 10 public class Singleton { private static Singleton instance; private static ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); public static Singleton getInstance() { lock.readLock().lock(); try { if (instance == null) { lock.readLock().unlock(); lock.writeLock().lock(); try { if (instance == null) { instance = new Singleton(); } } finally { lock.readLock().lock(); lock.writeLock().unlock(); } } return instance; } finally { lock.readLock().unlock(); } } private Singleton() {} }
  • 11.
    When should initializationhappen? • Double-checked locking (DCL) idiom 11 01. public class SingletonPattern 02. { 03. private volatile static SingletonPattern instance; 04. 05. private SingletonPattern() 06. {} 07. 08. public static SingletonPattern getInstance() 09. { 10. if (instance == null) { 11. synchronized (SingletonPattern.class) { 12. if (instance == null) 13. { 14. instance = new SingletonPattern(); 15. } 16. } 17. } 18. return instance; 19. } 20. }
  • 12.
    If Serializable isimplemented 12 public class Singleton implements Serializable { private static Singleton singleton = new Singleton(); private Singleton() { } // This method is called immediately after an object of // this class is deserialized. This method returns the // singleton instance. protected Object readResolve() { return singleton; } }
  • 13.
    If Cloneable isimplemented 13 public class Singleton implements Cloneable { private static Singleton singleton = new Singleton(); private Singleton() { } public Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); } }
  • 14.
    You can breakprevious implementations • If using java.lang.reflect package, • Or creating a custom ClassLoader 14 constructor.setAccessible (true);
  • 15.
    Enum singleton –the best way • Enum singleton doesn’t have protected/public constructors • It implements serializable and comparable • JVM ensures a single instance in multithreaded environment • Does not allow invocation of private constructors through reflection attacks 15 public enum SingletonEnum{ INSTANCE; public void someMethod() {} } SingletonEnum.INSTANCE.someMethod();
  • 16.