SlideShare a Scribd company logo
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

More Related Content

What's hot

Android Unit Test
Android Unit TestAndroid Unit Test
Android Unit Test
Phuoc Bui
 
Don't Make Android Bad... Again
Don't Make Android Bad... AgainDon't Make Android Bad... Again
Don't Make Android Bad... Again
Pedro Vicente
 
04 threads
04 threads04 threads
04 threads
ambar khetan
 
Java Deserialization Vulnerabilities - The Forgotten Bug Class (RuhrSec Edition)
Java Deserialization Vulnerabilities - The Forgotten Bug Class (RuhrSec Edition)Java Deserialization Vulnerabilities - The Forgotten Bug Class (RuhrSec Edition)
Java Deserialization Vulnerabilities - The Forgotten Bug Class (RuhrSec Edition)
CODE WHITE GmbH
 
Why using finalizers is a bad idea
Why using finalizers is a bad ideaWhy using finalizers is a bad idea
Why using finalizers is a bad idea
PVS-Studio
 
Singleton Pattern
Singleton PatternSingleton Pattern
Singleton Pattern
Borey Lim
 
Fixing the Java Serialization Mess
Fixing the Java Serialization Mess Fixing the Java Serialization Mess
Fixing the Java Serialization Mess
Salesforce Engineering
 
Reproducible component tests using docker
Reproducible component tests using dockerReproducible component tests using docker
Reproducible component tests using docker
Pavel Rabetski
 
Java Deserialization Vulnerabilities - The Forgotten Bug Class
Java Deserialization Vulnerabilities - The Forgotten Bug ClassJava Deserialization Vulnerabilities - The Forgotten Bug Class
Java Deserialization Vulnerabilities - The Forgotten Bug Class
CODE WHITE GmbH
 
Abusing Java Remote Interfaces
Abusing Java Remote InterfacesAbusing Java Remote Interfaces
Abusing Java Remote Interfaces
juanvazquezslides
 
OWASP SD: Deserialize My Shorts: Or How I Learned To Start Worrying and Hate ...
OWASP SD: Deserialize My Shorts: Or How I Learned To Start Worrying and Hate ...OWASP SD: Deserialize My Shorts: Or How I Learned To Start Worrying and Hate ...
OWASP SD: Deserialize My Shorts: Or How I Learned To Start Worrying and Hate ...
Christopher Frohoff
 
Defending against Java Deserialization Vulnerabilities
 Defending against Java Deserialization Vulnerabilities Defending against Java Deserialization Vulnerabilities
Defending against Java Deserialization Vulnerabilities
Luca Carettoni
 
JavaFX Dependency Injection with FxContainer
JavaFX Dependency Injection with FxContainerJavaFX Dependency Injection with FxContainer
JavaFX Dependency Injection with FxContainer
Srikanth Shenoy
 
ikp321-04
ikp321-04ikp321-04
ikp321-04
Anung Ariwibowo
 
Introduction+To+Java+Concurrency
Introduction+To+Java+ConcurrencyIntroduction+To+Java+Concurrency
Introduction+To+Java+Concurrency
King's College London
 
10 Typical Enterprise Java Problems
10 Typical Enterprise Java Problems10 Typical Enterprise Java Problems
10 Typical Enterprise Java Problems
Eberhard Wolff
 
Observer & singleton pattern
Observer  & singleton patternObserver  & singleton pattern
Observer & singleton pattern
babak danyal
 
Resting on your laurels will get you powned
Resting on your laurels will get you pownedResting on your laurels will get you powned
Resting on your laurels will get you powned
Dinis Cruz
 
An Overview of Deserialization Vulnerabilities in the Java Virtual Machine (J...
An Overview of Deserialization Vulnerabilities in the Java Virtual Machine (J...An Overview of Deserialization Vulnerabilities in the Java Virtual Machine (J...
An Overview of Deserialization Vulnerabilities in the Java Virtual Machine (J...
joaomatosf_
 
RxJava from the trenches
RxJava from the trenchesRxJava from the trenches
RxJava from the trenches
Peter Hendriks
 

What's hot (20)

Android Unit Test
Android Unit TestAndroid Unit Test
Android Unit Test
 
Don't Make Android Bad... Again
Don't Make Android Bad... AgainDon't Make Android Bad... Again
Don't Make Android Bad... Again
 
04 threads
04 threads04 threads
04 threads
 
Java Deserialization Vulnerabilities - The Forgotten Bug Class (RuhrSec Edition)
Java Deserialization Vulnerabilities - The Forgotten Bug Class (RuhrSec Edition)Java Deserialization Vulnerabilities - The Forgotten Bug Class (RuhrSec Edition)
Java Deserialization Vulnerabilities - The Forgotten Bug Class (RuhrSec Edition)
 
Why using finalizers is a bad idea
Why using finalizers is a bad ideaWhy using finalizers is a bad idea
Why using finalizers is a bad idea
 
Singleton Pattern
Singleton PatternSingleton Pattern
Singleton Pattern
 
Fixing the Java Serialization Mess
Fixing the Java Serialization Mess Fixing the Java Serialization Mess
Fixing the Java Serialization Mess
 
Reproducible component tests using docker
Reproducible component tests using dockerReproducible component tests using docker
Reproducible component tests using docker
 
Java Deserialization Vulnerabilities - The Forgotten Bug Class
Java Deserialization Vulnerabilities - The Forgotten Bug ClassJava Deserialization Vulnerabilities - The Forgotten Bug Class
Java Deserialization Vulnerabilities - The Forgotten Bug Class
 
Abusing Java Remote Interfaces
Abusing Java Remote InterfacesAbusing Java Remote Interfaces
Abusing Java Remote Interfaces
 
OWASP SD: Deserialize My Shorts: Or How I Learned To Start Worrying and Hate ...
OWASP SD: Deserialize My Shorts: Or How I Learned To Start Worrying and Hate ...OWASP SD: Deserialize My Shorts: Or How I Learned To Start Worrying and Hate ...
OWASP SD: Deserialize My Shorts: Or How I Learned To Start Worrying and Hate ...
 
Defending against Java Deserialization Vulnerabilities
 Defending against Java Deserialization Vulnerabilities Defending against Java Deserialization Vulnerabilities
Defending against Java Deserialization Vulnerabilities
 
JavaFX Dependency Injection with FxContainer
JavaFX Dependency Injection with FxContainerJavaFX Dependency Injection with FxContainer
JavaFX Dependency Injection with FxContainer
 
ikp321-04
ikp321-04ikp321-04
ikp321-04
 
Introduction+To+Java+Concurrency
Introduction+To+Java+ConcurrencyIntroduction+To+Java+Concurrency
Introduction+To+Java+Concurrency
 
10 Typical Enterprise Java Problems
10 Typical Enterprise Java Problems10 Typical Enterprise Java Problems
10 Typical Enterprise Java Problems
 
Observer & singleton pattern
Observer  & singleton patternObserver  & singleton pattern
Observer & singleton pattern
 
Resting on your laurels will get you powned
Resting on your laurels will get you pownedResting on your laurels will get you powned
Resting on your laurels will get you powned
 
An Overview of Deserialization Vulnerabilities in the Java Virtual Machine (J...
An Overview of Deserialization Vulnerabilities in the Java Virtual Machine (J...An Overview of Deserialization Vulnerabilities in the Java Virtual Machine (J...
An Overview of Deserialization Vulnerabilities in the Java Virtual Machine (J...
 
RxJava from the trenches
RxJava from the trenchesRxJava from the trenches
RxJava from the trenches
 

Viewers also liked

SSO with sfdc
SSO with sfdcSSO with sfdc
SSO with sfdc
Ming Yuan
 
Kiene3MPoster
Kiene3MPosterKiene3MPoster
Kiene3MPoster
Kelsea Kiene
 
Mission impossible the new beetle
Mission impossible the new beetleMission impossible the new beetle
Mission impossible the new beetle
Raj Kumar Singh
 
Consulting Partners - Lead Submission Porcess
Consulting Partners - Lead Submission PorcessConsulting Partners - Lead Submission Porcess
Consulting Partners - Lead Submission Porcess
Salesforce Partners
 
Lead Management using Sfdc
Lead Management using SfdcLead Management using Sfdc
Lead Management using Sfdc
Vinita Kapoor
 
Cross Functional Alignment Around the Customer Processes to Drive Success
Cross Functional Alignment Around the Customer Processes to Drive SuccessCross Functional Alignment Around the Customer Processes to Drive Success
Cross Functional Alignment Around the Customer Processes to Drive Success
Gainsight
 
Introduction to Salesforce.com
Introduction to Salesforce.comIntroduction to Salesforce.com
Introduction to Salesforce.com
Edureka!
 
Introduction to Salesforcedotcom
Introduction to SalesforcedotcomIntroduction to Salesforcedotcom
Introduction to Salesforcedotcom
Edureka!
 
Customer Relationship Management, Holcim Ltd.
Customer Relationship Management, Holcim Ltd.Customer Relationship Management, Holcim Ltd.
Customer Relationship Management, Holcim Ltd.
Isuru Asiri
 
SFDC - Step by Step Reference Guide
SFDC - Step by Step Reference GuideSFDC - Step by Step Reference Guide
SFDC - Step by Step Reference Guide
Kelsea Kiene
 
The Onboarding and Training Playbook
The Onboarding and Training PlaybookThe Onboarding and Training Playbook
The Onboarding and Training Playbook
Gainsight
 
QAP SFDC Development
QAP SFDC Development QAP SFDC Development
QAP SFDC Development
QAP INT
 
Salesforce Project in Mule ESB 3.6 and Above Using Query Builder
Salesforce Project in Mule ESB 3.6  and Above Using Query BuilderSalesforce Project in Mule ESB 3.6  and Above Using Query Builder
Salesforce Project in Mule ESB 3.6 and Above Using Query Builder
Sashidhar Rao GDS
 
SFDC Roll-Out v1c
SFDC Roll-Out v1cSFDC Roll-Out v1c
SFDC Roll-Out v1c
travisdow
 
SFDC Data Models For Pros - Simplifying The Complexities
SFDC Data Models For Pros - Simplifying The ComplexitiesSFDC Data Models For Pros - Simplifying The Complexities
SFDC Data Models For Pros - Simplifying The Complexities
Baruch Oxman
 
Whitebase : Assault Carrier for Micro-Services
Whitebase : Assault Carrier for Micro-ServicesWhitebase : Assault Carrier for Micro-Services
Whitebase : Assault Carrier for Micro-Services
Jaewoo Ahn
 
#SFDC #DF11
#SFDC #DF11#SFDC #DF11
#SFDC #DF11
Jukka Niiranen
 
Best Practices for API Management
Best Practices for API Management Best Practices for API Management
Best Practices for API Management
WSO2
 
Business Requirement Document
Business Requirement DocumentBusiness Requirement Document
Business Requirement Document
Hendrix Yapputro , Certified IT Architect
 
The Stackies: Marketing Technology Stack Awards, June 2015
The Stackies: Marketing Technology Stack Awards, June 2015The Stackies: Marketing Technology Stack Awards, June 2015
The Stackies: Marketing Technology Stack Awards, June 2015
Scott Brinker
 

Viewers also liked (20)

SSO with sfdc
SSO with sfdcSSO with sfdc
SSO with sfdc
 
Kiene3MPoster
Kiene3MPosterKiene3MPoster
Kiene3MPoster
 
Mission impossible the new beetle
Mission impossible the new beetleMission impossible the new beetle
Mission impossible the new beetle
 
Consulting Partners - Lead Submission Porcess
Consulting Partners - Lead Submission PorcessConsulting Partners - Lead Submission Porcess
Consulting Partners - Lead Submission Porcess
 
Lead Management using Sfdc
Lead Management using SfdcLead Management using Sfdc
Lead Management using Sfdc
 
Cross Functional Alignment Around the Customer Processes to Drive Success
Cross Functional Alignment Around the Customer Processes to Drive SuccessCross Functional Alignment Around the Customer Processes to Drive Success
Cross Functional Alignment Around the Customer Processes to Drive Success
 
Introduction to Salesforce.com
Introduction to Salesforce.comIntroduction to Salesforce.com
Introduction to Salesforce.com
 
Introduction to Salesforcedotcom
Introduction to SalesforcedotcomIntroduction to Salesforcedotcom
Introduction to Salesforcedotcom
 
Customer Relationship Management, Holcim Ltd.
Customer Relationship Management, Holcim Ltd.Customer Relationship Management, Holcim Ltd.
Customer Relationship Management, Holcim Ltd.
 
SFDC - Step by Step Reference Guide
SFDC - Step by Step Reference GuideSFDC - Step by Step Reference Guide
SFDC - Step by Step Reference Guide
 
The Onboarding and Training Playbook
The Onboarding and Training PlaybookThe Onboarding and Training Playbook
The Onboarding and Training Playbook
 
QAP SFDC Development
QAP SFDC Development QAP SFDC Development
QAP SFDC Development
 
Salesforce Project in Mule ESB 3.6 and Above Using Query Builder
Salesforce Project in Mule ESB 3.6  and Above Using Query BuilderSalesforce Project in Mule ESB 3.6  and Above Using Query Builder
Salesforce Project in Mule ESB 3.6 and Above Using Query Builder
 
SFDC Roll-Out v1c
SFDC Roll-Out v1cSFDC Roll-Out v1c
SFDC Roll-Out v1c
 
SFDC Data Models For Pros - Simplifying The Complexities
SFDC Data Models For Pros - Simplifying The ComplexitiesSFDC Data Models For Pros - Simplifying The Complexities
SFDC Data Models For Pros - Simplifying The Complexities
 
Whitebase : Assault Carrier for Micro-Services
Whitebase : Assault Carrier for Micro-ServicesWhitebase : Assault Carrier for Micro-Services
Whitebase : Assault Carrier for Micro-Services
 
#SFDC #DF11
#SFDC #DF11#SFDC #DF11
#SFDC #DF11
 
Best Practices for API Management
Best Practices for API Management Best Practices for API Management
Best Practices for API Management
 
Business Requirement Document
Business Requirement DocumentBusiness Requirement Document
Business Requirement Document
 
The Stackies: Marketing Technology Stack Awards, June 2015
The Stackies: Marketing Technology Stack Awards, June 2015The Stackies: Marketing Technology Stack Awards, June 2015
The Stackies: Marketing Technology Stack Awards, June 2015
 

Similar to Singleton

Lesson6
Lesson6Lesson6
Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017
Arsen Gasparyan
 
Meetup - Singleton & DI/IoC
Meetup - Singleton & DI/IoCMeetup - Singleton & DI/IoC
Meetup - Singleton & DI/IoC
Dusan Zamurovic
 
Javascript Common Design Patterns
Javascript Common Design PatternsJavascript Common Design Patterns
Javascript Common Design Patterns
Pham Huy Tung
 
Singleton Pattern
Singleton PatternSingleton Pattern
Singleton Pattern
Hany Omar
 
Creating and destroying objects
Creating and destroying objectsCreating and destroying objects
Creating and destroying objects
Sandeep Chawla
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency Gotchas
Alex Miller
 
Java 5 concurrency
Java 5 concurrencyJava 5 concurrency
Java 5 concurrency
priyank09
 
Introduction to design_patterns
Introduction to design_patternsIntroduction to design_patterns
Introduction to design_patterns
amitarcade
 
Singleton design pattern
Singleton design patternSingleton design pattern
Singleton design pattern
11prasoon
 
Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...
go_oh
 
Java Serialization
Java SerializationJava Serialization
Java Serialization
imypraz
 
Coroutines for Kotlin Multiplatform in Practise
Coroutines for Kotlin Multiplatform in PractiseCoroutines for Kotlin Multiplatform in Practise
Coroutines for Kotlin Multiplatform in Practise
Christian Melchior
 
Singleton Object Management
Singleton Object ManagementSingleton Object Management
Singleton Object Management
ppd1961
 
Design patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjsDesign patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjs
Ravi Bhadauria
 
Effective Java - Override clone() method judiciously
Effective Java - Override clone() method judiciouslyEffective Java - Override clone() method judiciously
Effective Java - Override clone() method judiciously
Ferdous Mahmud Shaon
 
Concurrency Antipatterns In IDEA
Concurrency Antipatterns In IDEAConcurrency Antipatterns In IDEA
Concurrency Antipatterns In IDEA
cdracm
 
谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testability谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testability
drewz lin
 
Android & Kotlin - The code awakens #01
Android & Kotlin - The code awakens #01Android & Kotlin - The code awakens #01
Android & Kotlin - The code awakens #01
Omar Miatello
 
第1回 チキチキ『( ゜ェ゜)・;'.、ゴフッ』 - シングルトンパターン(Java)
第1回 チキチキ『( ゜ェ゜)・;'.、ゴフッ』 - シングルトンパターン(Java)第1回 チキチキ『( ゜ェ゜)・;'.、ゴフッ』 - シングルトンパターン(Java)
第1回 チキチキ『( ゜ェ゜)・;'.、ゴフッ』 - シングルトンパターン(Java)
潤一 加藤
 

Similar to Singleton (20)

Lesson6
Lesson6Lesson6
Lesson6
 
Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017
 
Meetup - Singleton & DI/IoC
Meetup - Singleton & DI/IoCMeetup - Singleton & DI/IoC
Meetup - Singleton & DI/IoC
 
Javascript Common Design Patterns
Javascript Common Design PatternsJavascript Common Design Patterns
Javascript Common Design Patterns
 
Singleton Pattern
Singleton PatternSingleton Pattern
Singleton Pattern
 
Creating and destroying objects
Creating and destroying objectsCreating and destroying objects
Creating and destroying objects
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency Gotchas
 
Java 5 concurrency
Java 5 concurrencyJava 5 concurrency
Java 5 concurrency
 
Introduction to design_patterns
Introduction to design_patternsIntroduction to design_patterns
Introduction to design_patterns
 
Singleton design pattern
Singleton design patternSingleton design pattern
Singleton design pattern
 
Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...
 
Java Serialization
Java SerializationJava Serialization
Java Serialization
 
Coroutines for Kotlin Multiplatform in Practise
Coroutines for Kotlin Multiplatform in PractiseCoroutines for Kotlin Multiplatform in Practise
Coroutines for Kotlin Multiplatform in Practise
 
Singleton Object Management
Singleton Object ManagementSingleton Object Management
Singleton Object Management
 
Design patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjsDesign patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjs
 
Effective Java - Override clone() method judiciously
Effective Java - Override clone() method judiciouslyEffective Java - Override clone() method judiciously
Effective Java - Override clone() method judiciously
 
Concurrency Antipatterns In IDEA
Concurrency Antipatterns In IDEAConcurrency Antipatterns In IDEA
Concurrency Antipatterns In IDEA
 
谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testability谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testability
 
Android & Kotlin - The code awakens #01
Android & Kotlin - The code awakens #01Android & Kotlin - The code awakens #01
Android & Kotlin - The code awakens #01
 
第1回 チキチキ『( ゜ェ゜)・;'.、ゴフッ』 - シングルトンパターン(Java)
第1回 チキチキ『( ゜ェ゜)・;'.、ゴフッ』 - シングルトンパターン(Java)第1回 チキチキ『( ゜ェ゜)・;'.、ゴフッ』 - シングルトンパターン(Java)
第1回 チキチキ『( ゜ェ゜)・;'.、ゴフッ』 - シングルトンパターン(Java)
 

More from Ming Yuan

Cloud and Analytics -- 2020 sparksummit
Cloud and Analytics -- 2020 sparksummitCloud and Analytics -- 2020 sparksummit
Cloud and Analytics -- 2020 sparksummit
Ming Yuan
 
Forrester2019
Forrester2019Forrester2019
Forrester2019
Ming Yuan
 
R & Python on Hadoop
R & Python on HadoopR & Python on Hadoop
R & Python on Hadoop
Ming Yuan
 
Rest and beyond
Rest and beyondRest and beyond
Rest and beyond
Ming Yuan
 
Simplifying Apache Cascading
Simplifying Apache CascadingSimplifying Apache Cascading
Simplifying Apache Cascading
Ming Yuan
 
Building calloutswithoutwsdl2apex
Building calloutswithoutwsdl2apexBuilding calloutswithoutwsdl2apex
Building calloutswithoutwsdl2apex
Ming Yuan
 

More from Ming Yuan (6)

Cloud and Analytics -- 2020 sparksummit
Cloud and Analytics -- 2020 sparksummitCloud and Analytics -- 2020 sparksummit
Cloud and Analytics -- 2020 sparksummit
 
Forrester2019
Forrester2019Forrester2019
Forrester2019
 
R & Python on Hadoop
R & Python on HadoopR & Python on Hadoop
R & Python on Hadoop
 
Rest and beyond
Rest and beyondRest and beyond
Rest and beyond
 
Simplifying Apache Cascading
Simplifying Apache CascadingSimplifying Apache Cascading
Simplifying Apache Cascading
 
Building calloutswithoutwsdl2apex
Building calloutswithoutwsdl2apexBuilding calloutswithoutwsdl2apex
Building calloutswithoutwsdl2apex
 

Recently uploaded

Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...
Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...
Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...
Zilliz
 
20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website
Pixlogix Infotech
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIEnchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Vladimir Iglovikov, Ph.D.
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
SOFTTECHHUB
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
Adtran
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
Neo4j
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc
 
“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”
Claudio Di Ciccio
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
Daiki Mogmet Ito
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 

Recently uploaded (20)

Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...
Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...
Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...
 
20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIEnchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
 
“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 

Singleton

  • 1. 1 The Singleton pattern and implementations Ming Yuan October, 2013
  • 2. 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
  • 3. The Singleton design pattern • Ensure a class only has one instance per ???? 3
  • 4. 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
  • 5. 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. }
  • 6. 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. }
  • 7. 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. }
  • 8. 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. }
  • 9. 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. }
  • 10. 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() {} }
  • 11. 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. }
  • 12. 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; } }
  • 13. 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(); } }
  • 14. You can break previous 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();