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
PPTX
Singleton Design Pattern - Creation Pattern
PPTX
Singleton Pattern (Sole Object with Global Access)
PPT
Introduction to Design Patterns and Singleton
PPTX
Singleton Pattern
PPTX
Design Pattern - Singleton Pattern
PPT
Singleton design pattern
PPTX
Singleton Pattern
The Singleton Pattern Presentation
Singleton Design Pattern - Creation Pattern
Singleton Pattern (Sole Object with Global Access)
Introduction to Design Patterns and Singleton
Singleton Pattern
Design Pattern - Singleton Pattern
Singleton design pattern
Singleton Pattern

What's hot (20)

PPTX
Observer & singleton pattern
PPT
Java Serialization
PDF
Serialization & De-serialization in Java
PDF
Annotation Processing in Android
PDF
An Introduction To Unit Testing and TDD
PDF
Java exception handling
PDF
Unit testing in xcode 8 with swift
PDF
Java Programming - 04 object oriented in java
PPTX
Serialization in java
PPS
Java Exception handling
PPTX
Unit 1 of java part 2 basic introduction
PDF
All about unit testing using (power) mock
PPTX
Java I/O and Object Serialization
PDF
Java Serialization Deep Dive
PPTX
JAVA - Throwable class
PDF
Java multi threading and synchronization
PPTX
TestNG vs JUnit: cease fire or the end of the war
PDF
Java Serialization
PPTX
Java applet
PPTX
Java concurrency in practice
Observer & singleton pattern
Java Serialization
Serialization & De-serialization in Java
Annotation Processing in Android
An Introduction To Unit Testing and TDD
Java exception handling
Unit testing in xcode 8 with swift
Java Programming - 04 object oriented in java
Serialization in java
Java Exception handling
Unit 1 of java part 2 basic introduction
All about unit testing using (power) mock
Java I/O and Object Serialization
Java Serialization Deep Dive
JAVA - Throwable class
Java multi threading and synchronization
TestNG vs JUnit: cease fire or the end of the war
Java Serialization
Java applet
Java concurrency in practice
Ad

Similar to Java - Singleton Pattern (20)

PPT
Singleton
PDF
Singleton Sum
PDF
The Singleton Pattern In Java
PDF
From Runnable and synchronized To atomically() and parallel()
PPTX
Singleton class in Java
PDF
Java Concurrency Gotchas
PDF
Java Concurrency Gotchas
PDF
Javaoneconcurrencygotchas 090610192215 Phpapp02
PPTX
Creating and destroying objects
PPT
Java Objects Constructed Within The Final Field Safe Context
PPT
Concurrency Antipatterns In IDEA
ODP
Effective java - Creating and Destroying Objects
PPTX
Java concurrency
PDF
Robust and Scalable Concurrent Programming: Lesson from the Trenches
PDF
Singleton Pattern
PPTX
Advanced Introduction to Java Multi-Threading - Full (chok)
PPTX
Java_Interview Qns
PDF
Singleton 패턴 (김진영 - EVA, 소마에 10기)
PPS
Singletons
PDF
Design patterns in Java - Monitis 2017
Singleton
Singleton Sum
The Singleton Pattern In Java
From Runnable and synchronized To atomically() and parallel()
Singleton class in Java
Java Concurrency Gotchas
Java Concurrency Gotchas
Javaoneconcurrencygotchas 090610192215 Phpapp02
Creating and destroying objects
Java Objects Constructed Within The Final Field Safe Context
Concurrency Antipatterns In IDEA
Effective java - Creating and Destroying Objects
Java concurrency
Robust and Scalable Concurrent Programming: Lesson from the Trenches
Singleton Pattern
Advanced Introduction to Java Multi-Threading - Full (chok)
Java_Interview Qns
Singleton 패턴 (김진영 - EVA, 소마에 10기)
Singletons
Design patterns in Java - Monitis 2017
Ad

Recently uploaded (20)

PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PDF
Digital Strategies for Manufacturing Companies
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PPTX
Mini project ppt template for panimalar Engineering college
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PDF
System and Network Administraation Chapter 3
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PDF
PTS Company Brochure 2025 (1).pdf.......
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PPTX
Introduction to Artificial Intelligence
PDF
A REACT POMODORO TIMER WEB APPLICATION.pdf
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PPTX
Odoo POS Development Services by CandidRoot Solutions
PPT
JAVA ppt tutorial basics to learn java programming
PDF
Softaken Excel to vCard Converter Software.pdf
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PDF
AI in Product Development-omnex systems
PDF
How Creative Agencies Leverage Project Management Software.pdf
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
Digital Strategies for Manufacturing Companies
2025 Textile ERP Trends: SAP, Odoo & Oracle
Mini project ppt template for panimalar Engineering college
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
System and Network Administraation Chapter 3
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PTS Company Brochure 2025 (1).pdf.......
How to Choose the Right IT Partner for Your Business in Malaysia
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
Introduction to Artificial Intelligence
A REACT POMODORO TIMER WEB APPLICATION.pdf
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
Upgrade and Innovation Strategies for SAP ERP Customers
Odoo POS Development Services by CandidRoot Solutions
JAVA ppt tutorial basics to learn java programming
Softaken Excel to vCard Converter Software.pdf
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
AI in Product Development-omnex systems
How Creative Agencies Leverage Project Management Software.pdf

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