SlideShare a Scribd company logo
TheSingleton Pattern
…because we all use it but…
Singleton
Pattern
Singleton
Pattern
1 & 1 instance
universal access
prevents/controls
concurrency
Singleton
Pattern
logging
database
access
class
loaders
factories
Basic
Singleton
BasicSingleton
no new
utility
method
static
method
static
instance
BasicSingleton
// Minimal Singleton (or is it ?), can’t handle pre-conditions
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {
if (INSTANCE != null) {
throw new IllegalStateException("Woops, the matrix is broken");
}
}
public static Singleton getInstance() {
return INSTANCE;
}
}
BasicSingleton
// Same as before, can handle pre-conditions through static init. block
public class Singleton {
private static Singleton INSTANCE;
static {
try {
INSTANCE = new Singleton();
} catch (Exception ex) {
throw new RuntimeException("A damn error occured!", ex);
}
}
private Singleton() {
// Same as before
}
public static Singleton getInstance() {
return INSTANCE;
}
}
Broken Idioms
Broken Idioms
Instance not initialized, no sync
// Seems right, at first, but what about concurrency ?
public class Singleton {
private static Singleton INSTANCE = null;
private Singleton() {
// Nothing
}
public static Singleton getInstance() {
if (INSTANCE == null) {
INSTANCE = new Singleton();
}
return INSTANCE;
}
}
Broken Idioms
Synchronized getInstance()
// Concurrency issue fixed, but very slow
public class Singleton {
private static Singleton INSTANCE = null;
private Singleton() {
// Nothing
}
public static synchronized Singleton getInstance() {
if (INSTANCE == null) {
INSTANCE = new Singleton();
}
return INSTANCE;
}
}
Broken Idioms
Double checked locking
// Does not work this way, broken due to compiler re-ordering
public class Singleton {
private static Singleton INSTANCE = null;
private Singleton() { }
public static Singleton getInstance() {
if (INSTANCE == null) {
synchronized (Singleton.class) {
if (INSTANCE == null) {
INSTANCE = new Singleton();
}
}
}
return INSTANCE;
}
}
Basic
Singleton 2
Basic
Singleton 2
The Holder, proposed by Bill Pugh
//No language construct, relies on JVM memory model properties, very lazy
public class Singleton {
private Singleton() {
// Nothing
}
// Loaded on the 1st exec of Singleton.getInstance(), not before
private static class SingletonHolder {
public static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
EnumSingleton
EnumSingleton
have
methods
can
implements
interface
static
instances
free
thread safe*
* only if
there is no
state
serializable
EnumSingleton
Proposed by Joshua Bloch
// OK in most cases, can be hacked by malicious serialized form
public enum Elvis implements Singer,Zombie {
ELVIS;
@Override
public void singASong() {
// …
}
@Override
public void eatBrains() {
// …
}
}
Serializable
Singleton
EnumSingleton
NO
STATE
Serializable
Singleton
Part 1
public class Elvis implements Serializable {
private static final Elvis INSTANCE = new Elvis();
private static final long serialVersionUID = 42L;
private volatile String[] songs = {"Hound Dog", "Heartbreak Hotel"};
public static Elvis getInstance() { return INSTANCE; }
private Elvis() { }
public void leaveTheBuilding() { }
public void setFavouriteSongs(String[] songs) {
this.songs = songs.clone();
}
public void printFavorites() {
System.out.println(Arrays.toString(songs));
}
Serializable
Singleton
Part 2
// this should never be invoked
private Object readResolve() {
return INSTANCE;
}
private void readObject(ObjectInputStream ex) throws IOException {
throw new InvalidObjectException("Cannot load another Elvis");
}
private Object writeReplace() {
return new ElvisSerializableForm(songs);
}
Serializable
Singleton
Part 3
private Object writeReplace() {
return new ElvisSerializableForm(songs);
}
private static class ElvisSerializableForm implements Serializable {
private final String[] songs;
public ElvisSerializableForm(String[] favoriteSongs) {
this.songs = favoriteSongs;
}
publicObject readResolve() {
Elvis.INSTANCE.setFavouriteSongs(songs);
return Elvis.INSTANCE;
}
}
}
Singletons are
Armful
Singletons are
Armful
global state
hard to test
hard coded
dependencies
Similar to
Village of the
Damned
design anti-
pattern
Might be OK
if there is NO
STATE
use IoC for
factories
Singletons
Singletons
Use enums
Use « Lazy Holders »
Beware of Serialization
Singleton are Armful
Don’t use them
Singletons
Quizz
Fixing the broken ones
A double fix
Fixing double checked locking
// Does not work this way, broken due to compiler re-ordering
public class Singleton {
private static Singleton INSTANCE = null;
private Singleton() { }
public static Singleton getInstance() {
if (INSTANCE == null) {
synchronized (Singleton.class) {
if (INSTANCE == null) {
INSTANCE = new Singleton();
}
}
}
return INSTANCE;
}
}
A double fix
Fixing double checked locking
//The right word, at the right time, in the right place can make a difference
public class Singleton {
private static volatile Singleton INSTANCE = null;
private Singleton() { }
public static Singleton getInstance() {
if (INSTANCE == null) {
synchronized (Singleton.class) {
if (INSTANCE == null) {
INSTANCE = new Singleton();
}
}
}
return INSTANCE;
}
}
Biblio
Biblio
 Bloch, Joshua. EffectiveJava,Second Edition. O’Reilly, 2008
 Croisier, Olivier. De la bonne implémentation du Singleton en Java.
2008.
http://thecodersbreakfast.net/index.php?post/2008/02/25/26-de-
la-bonne-implementation-du-singleton-en-java
 Hevery, Miško. Root Cause of Singletons, 2008.
http://misko.hevery.com/2008/08/25/root-cause-of-singletons/
 Hevery, Miško. Singleton are Pathlogical Liars, 2008.
http://misko.hevery.com/2008/08/17/singletons-are-pathological-
liars/
Biblio
 Hevery, Miško. Where Have All the Singletons Gone ?, 2008.
http://misko.hevery.com/2008/08/21/where-have-all-the-
singletons-gone/
 Kabutz, Heinz. The Java Specialists’ Newsletter #163, 2008.
http://www.javaspecialists.eu/archive/Issue163.html
 Manson, Jeremy. Double Checked Locking, 2008.
http://jeremymanson.blogspot.fr/2008/05/double-checked-
locking.html
 Pugh, Bill. The « Double-Checked Locking is Broken » Declaration.
http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleChecke
dLocking.html
Biblio
 Pugh, Bill. The Java Memory Model, 2004.
http://www.cs.umd.edu/~pugh/java/memoryModel/
 Pugh, Bill. JSR 133 (Java Memory Model) FAQ, 2004.
http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-
faq.html
 Wikipedia, Initialization-on-demand holder idiom.
http://en.wikipedia.org/wiki/Initialization-on-
demand_holder_idiom
 Wikipedia, Singleton pattern.
http://en.wikipedia.org/wiki/Singleton_pattern

More Related Content

PPTX
The Singleton Pattern Presentation
JAINIK PATEL
 
PPTX
Singleton Design Pattern - Creation Pattern
Seerat Malik
 
PPTX
Singleton Pattern (Sole Object with Global Access)
Sameer Rathoud
 
PPT
Introduction to Design Patterns and Singleton
Jonathan Simon
 
PPTX
Singleton Pattern
Borey Lim
 
PPTX
Design Pattern - Singleton Pattern
Mudasir Qazi
 
PPT
Singleton design pattern
11prasoon
 
PPTX
Singleton Pattern
Reber Novanta
 
The Singleton Pattern Presentation
JAINIK PATEL
 
Singleton Design Pattern - Creation Pattern
Seerat Malik
 
Singleton Pattern (Sole Object with Global Access)
Sameer Rathoud
 
Introduction to Design Patterns and Singleton
Jonathan Simon
 
Singleton Pattern
Borey Lim
 
Design Pattern - Singleton Pattern
Mudasir Qazi
 
Singleton design pattern
11prasoon
 
Singleton Pattern
Reber Novanta
 

What's hot (20)

PPTX
Observer & singleton pattern
babak danyal
 
PPT
Java Serialization
jeslie
 
PDF
Serialization & De-serialization in Java
InnovationM
 
PDF
Annotation Processing in Android
emanuelez
 
PDF
An Introduction To Unit Testing and TDD
Ahmed Ehab AbdulAziz
 
PDF
Java exception handling
rithustutorials
 
PDF
Unit testing in xcode 8 with swift
allanh0526
 
PDF
Java Programming - 04 object oriented in java
Danairat Thanabodithammachari
 
PPTX
Serialization in java
Janu Jahnavi
 
PPS
Java Exception handling
kamal kotecha
 
PPTX
Unit 1 of java part 2 basic introduction
AKR Education
 
PDF
All about unit testing using (power) mock
Pranalee Rokde
 
PPTX
Java I/O and Object Serialization
Navneet Prakash
 
PDF
Java Serialization Deep Dive
Martijn Dashorst
 
PPTX
JAVA - Throwable class
asifpatel20
 
PDF
Java multi threading and synchronization
rithustutorials
 
PPTX
TestNG vs JUnit: cease fire or the end of the war
Oleksiy Rezchykov
 
PDF
Java Serialization
imypraz
 
PPTX
Java applet
Elizabeth alexander
 
PPTX
Java concurrency in practice
Mikalai Alimenkou
 
Observer & singleton pattern
babak danyal
 
Java Serialization
jeslie
 
Serialization & De-serialization in Java
InnovationM
 
Annotation Processing in Android
emanuelez
 
An Introduction To Unit Testing and TDD
Ahmed Ehab AbdulAziz
 
Java exception handling
rithustutorials
 
Unit testing in xcode 8 with swift
allanh0526
 
Java Programming - 04 object oriented in java
Danairat Thanabodithammachari
 
Serialization in java
Janu Jahnavi
 
Java Exception handling
kamal kotecha
 
Unit 1 of java part 2 basic introduction
AKR Education
 
All about unit testing using (power) mock
Pranalee Rokde
 
Java I/O and Object Serialization
Navneet Prakash
 
Java Serialization Deep Dive
Martijn Dashorst
 
JAVA - Throwable class
asifpatel20
 
Java multi threading and synchronization
rithustutorials
 
TestNG vs JUnit: cease fire or the end of the war
Oleksiy Rezchykov
 
Java Serialization
imypraz
 
Java applet
Elizabeth alexander
 
Java concurrency in practice
Mikalai Alimenkou
 
Ad

Similar to Java - Singleton Pattern (15)

PDF
Singleton Pattern
Hany Omar
 
PPTX
Meetup - Singleton & DI/IoC
Dusan Zamurovic
 
PPT
Singleton
Ming Yuan
 
PDF
Design patterns in Java - Monitis 2017
Arsen Gasparyan
 
PDF
Singleton Sum
Slim Ouertani
 
KEY
第1回 チキチキ『( ゜ェ゜)・;'.、ゴフッ』 - シングルトンパターン(Java)
潤一 加藤
 
PDF
Java Concurrency Gotchas
Alex Miller
 
PDF
Java serialization
Ecommerce Solution Provider SysIQ
 
PPT
Singleton Object Management
ppd1961
 
PPTX
Singleton class in Java
Rahul Sharma
 
PPT
04 threads
ambar khetan
 
PDF
Java Design Patterns: The State Pattern
Antony Quinn
 
PPT
Concurrency Antipatterns In IDEA
cdracm
 
DOCX
Java 5 concurrency
priyank09
 
PPTX
Java For Automation
Abhijeet Dubey
 
Singleton Pattern
Hany Omar
 
Meetup - Singleton & DI/IoC
Dusan Zamurovic
 
Singleton
Ming Yuan
 
Design patterns in Java - Monitis 2017
Arsen Gasparyan
 
Singleton Sum
Slim Ouertani
 
第1回 チキチキ『( ゜ェ゜)・;'.、ゴフッ』 - シングルトンパターン(Java)
潤一 加藤
 
Java Concurrency Gotchas
Alex Miller
 
Singleton Object Management
ppd1961
 
Singleton class in Java
Rahul Sharma
 
04 threads
ambar khetan
 
Java Design Patterns: The State Pattern
Antony Quinn
 
Concurrency Antipatterns In IDEA
cdracm
 
Java 5 concurrency
priyank09
 
Java For Automation
Abhijeet Dubey
 
Ad

Recently uploaded (20)

PDF
Appium Automation Testing Tutorial PDF: Learn Mobile Testing in 7 Days
jamescantor38
 
PDF
The Role of Automation and AI in EHS Management for Data Centers.pdf
TECH EHS Solution
 
PDF
Micromaid: A simple Mermaid-like chart generator for Pharo
ESUG
 
PPTX
slidesgo-unlocking-the-code-the-dynamic-dance-of-variables-and-constants-2024...
kr2589474
 
PPTX
Maximizing Revenue with Marketo Measure: A Deep Dive into Multi-Touch Attribu...
bbedford2
 
PDF
What to consider before purchasing Microsoft 365 Business Premium_PDF.pdf
Q-Advise
 
PPTX
Role Of Python In Programing Language.pptx
jaykoshti048
 
PPTX
ASSIGNMENT_1[1][1][1][1][1] (1) variables.pptx
kr2589474
 
DOCX
The Future of Smart Factories Why Embedded Analytics Leads the Way
Varsha Nayak
 
PDF
Community & News Update Q2 Meet Up 2025
VictoriaMetrics
 
PDF
Teaching Reproducibility and Embracing Variability: From Floating-Point Exper...
University of Rennes, INSA Rennes, Inria/IRISA, CNRS
 
PDF
On Software Engineers' Productivity - Beyond Misleading Metrics
Romén Rodríguez-Gil
 
PDF
Why Use Open Source Reporting Tools for Business Intelligence.pdf
Varsha Nayak
 
PDF
QAware_Mario-Leander_Reimer_Architecting and Building a K8s-based AI Platform...
QAware GmbH
 
PDF
Exploring AI Agents in Process Industries
amoreira6
 
PPTX
Explanation about Structures in C language.pptx
Veeral Rathod
 
PDF
Jenkins: An open-source automation server powering CI/CD Automation
SaikatBasu37
 
PPTX
Why Use Open Source Reporting Tools for Business Intelligence.pptx
Varsha Nayak
 
PDF
Become an Agentblazer Champion Challenge Kickoff
Dele Amefo
 
PPTX
ConcordeApp: Engineering Global Impact & Unlocking Billions in Event ROI with AI
chastechaste14
 
Appium Automation Testing Tutorial PDF: Learn Mobile Testing in 7 Days
jamescantor38
 
The Role of Automation and AI in EHS Management for Data Centers.pdf
TECH EHS Solution
 
Micromaid: A simple Mermaid-like chart generator for Pharo
ESUG
 
slidesgo-unlocking-the-code-the-dynamic-dance-of-variables-and-constants-2024...
kr2589474
 
Maximizing Revenue with Marketo Measure: A Deep Dive into Multi-Touch Attribu...
bbedford2
 
What to consider before purchasing Microsoft 365 Business Premium_PDF.pdf
Q-Advise
 
Role Of Python In Programing Language.pptx
jaykoshti048
 
ASSIGNMENT_1[1][1][1][1][1] (1) variables.pptx
kr2589474
 
The Future of Smart Factories Why Embedded Analytics Leads the Way
Varsha Nayak
 
Community & News Update Q2 Meet Up 2025
VictoriaMetrics
 
Teaching Reproducibility and Embracing Variability: From Floating-Point Exper...
University of Rennes, INSA Rennes, Inria/IRISA, CNRS
 
On Software Engineers' Productivity - Beyond Misleading Metrics
Romén Rodríguez-Gil
 
Why Use Open Source Reporting Tools for Business Intelligence.pdf
Varsha Nayak
 
QAware_Mario-Leander_Reimer_Architecting and Building a K8s-based AI Platform...
QAware GmbH
 
Exploring AI Agents in Process Industries
amoreira6
 
Explanation about Structures in C language.pptx
Veeral Rathod
 
Jenkins: An open-source automation server powering CI/CD Automation
SaikatBasu37
 
Why Use Open Source Reporting Tools for Business Intelligence.pptx
Varsha Nayak
 
Become an Agentblazer Champion Challenge Kickoff
Dele Amefo
 
ConcordeApp: Engineering Global Impact & Unlocking Billions in Event ROI with AI
chastechaste14
 

Java - Singleton Pattern

  • 3. Singleton Pattern 1 & 1 instance universal access prevents/controls concurrency
  • 7. BasicSingleton // Minimal Singleton (or is it ?), can’t handle pre-conditions public class Singleton { private static final Singleton INSTANCE = new Singleton(); private Singleton() { if (INSTANCE != null) { throw new IllegalStateException("Woops, the matrix is broken"); } } public static Singleton getInstance() { return INSTANCE; } }
  • 8. BasicSingleton // Same as before, can handle pre-conditions through static init. block public class Singleton { private static Singleton INSTANCE; static { try { INSTANCE = new Singleton(); } catch (Exception ex) { throw new RuntimeException("A damn error occured!", ex); } } private Singleton() { // Same as before } public static Singleton getInstance() { return INSTANCE; } }
  • 10. Broken Idioms Instance not initialized, no sync // Seems right, at first, but what about concurrency ? public class Singleton { private static Singleton INSTANCE = null; private Singleton() { // Nothing } public static Singleton getInstance() { if (INSTANCE == null) { INSTANCE = new Singleton(); } return INSTANCE; } }
  • 11. Broken Idioms Synchronized getInstance() // Concurrency issue fixed, but very slow public class Singleton { private static Singleton INSTANCE = null; private Singleton() { // Nothing } public static synchronized Singleton getInstance() { if (INSTANCE == null) { INSTANCE = new Singleton(); } return INSTANCE; } }
  • 12. Broken Idioms Double checked locking // Does not work this way, broken due to compiler re-ordering public class Singleton { private static Singleton INSTANCE = null; private Singleton() { } public static Singleton getInstance() { if (INSTANCE == null) { synchronized (Singleton.class) { if (INSTANCE == null) { INSTANCE = new Singleton(); } } } return INSTANCE; } }
  • 14. Basic Singleton 2 The Holder, proposed by Bill Pugh //No language construct, relies on JVM memory model properties, very lazy public class Singleton { private Singleton() { // Nothing } // Loaded on the 1st exec of Singleton.getInstance(), not before private static class SingletonHolder { public static final Singleton INSTANCE = new Singleton(); } public static Singleton getInstance() { return SingletonHolder.INSTANCE; } }
  • 17. EnumSingleton Proposed by Joshua Bloch // OK in most cases, can be hacked by malicious serialized form public enum Elvis implements Singer,Zombie { ELVIS; @Override public void singASong() { // … } @Override public void eatBrains() { // … } }
  • 20. Serializable Singleton Part 1 public class Elvis implements Serializable { private static final Elvis INSTANCE = new Elvis(); private static final long serialVersionUID = 42L; private volatile String[] songs = {"Hound Dog", "Heartbreak Hotel"}; public static Elvis getInstance() { return INSTANCE; } private Elvis() { } public void leaveTheBuilding() { } public void setFavouriteSongs(String[] songs) { this.songs = songs.clone(); } public void printFavorites() { System.out.println(Arrays.toString(songs)); }
  • 21. Serializable Singleton Part 2 // this should never be invoked private Object readResolve() { return INSTANCE; } private void readObject(ObjectInputStream ex) throws IOException { throw new InvalidObjectException("Cannot load another Elvis"); } private Object writeReplace() { return new ElvisSerializableForm(songs); }
  • 22. Serializable Singleton Part 3 private Object writeReplace() { return new ElvisSerializableForm(songs); } private static class ElvisSerializableForm implements Serializable { private final String[] songs; public ElvisSerializableForm(String[] favoriteSongs) { this.songs = favoriteSongs; } publicObject readResolve() { Elvis.INSTANCE.setFavouriteSongs(songs); return Elvis.INSTANCE; } } }
  • 24. Singletons are Armful global state hard to test hard coded dependencies Similar to Village of the Damned design anti- pattern Might be OK if there is NO STATE use IoC for factories
  • 26. Singletons Use enums Use « Lazy Holders » Beware of Serialization Singleton are Armful Don’t use them
  • 29. A double fix Fixing double checked locking // Does not work this way, broken due to compiler re-ordering public class Singleton { private static Singleton INSTANCE = null; private Singleton() { } public static Singleton getInstance() { if (INSTANCE == null) { synchronized (Singleton.class) { if (INSTANCE == null) { INSTANCE = new Singleton(); } } } return INSTANCE; } }
  • 30. A double fix Fixing double checked locking //The right word, at the right time, in the right place can make a difference public class Singleton { private static volatile Singleton INSTANCE = null; private Singleton() { } public static Singleton getInstance() { if (INSTANCE == null) { synchronized (Singleton.class) { if (INSTANCE == null) { INSTANCE = new Singleton(); } } } return INSTANCE; } }
  • 32. Biblio  Bloch, Joshua. EffectiveJava,Second Edition. O’Reilly, 2008  Croisier, Olivier. De la bonne implémentation du Singleton en Java. 2008. http://thecodersbreakfast.net/index.php?post/2008/02/25/26-de- la-bonne-implementation-du-singleton-en-java  Hevery, Miško. Root Cause of Singletons, 2008. http://misko.hevery.com/2008/08/25/root-cause-of-singletons/  Hevery, Miško. Singleton are Pathlogical Liars, 2008. http://misko.hevery.com/2008/08/17/singletons-are-pathological- liars/
  • 33. Biblio  Hevery, Miško. Where Have All the Singletons Gone ?, 2008. http://misko.hevery.com/2008/08/21/where-have-all-the- singletons-gone/  Kabutz, Heinz. The Java Specialists’ Newsletter #163, 2008. http://www.javaspecialists.eu/archive/Issue163.html  Manson, Jeremy. Double Checked Locking, 2008. http://jeremymanson.blogspot.fr/2008/05/double-checked- locking.html  Pugh, Bill. The « Double-Checked Locking is Broken » Declaration. http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleChecke dLocking.html
  • 34. Biblio  Pugh, Bill. The Java Memory Model, 2004. http://www.cs.umd.edu/~pugh/java/memoryModel/  Pugh, Bill. JSR 133 (Java Memory Model) FAQ, 2004. http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133- faq.html  Wikipedia, Initialization-on-demand holder idiom. http://en.wikipedia.org/wiki/Initialization-on- demand_holder_idiom  Wikipedia, Singleton pattern. http://en.wikipedia.org/wiki/Singleton_pattern