SlideShare a Scribd company logo
1 of 13
Download to read offline
Singleton
       Singleton pattern in java enterprise world
                   Slim Ouertani
                         
Intent

    Ensure a class only has one instance, and 
    provide a global point of access to it. [GoF p 
    119]




                            
Motivation



    
        It's important for some classes to have exactly one 
        instance. Although there can be many printers in a 
        system, there should be only one printer spooler.
    
        How do we ensure that a class has only one instance 
        and that the instance is easily accessible?
    
        A global variable makes an object accessible, but it 
        doesn't keep you from instantiating multiple objects.



                                   
Motivation


    A better solution is to make the class itself responsible 
    for keeping track of its sole instance. 
    The  class  can  ensure  that  no  other  instance  can  be 
    created  (by  intercepting  requests  to  create  new 
    objects),  and  it  can  provide  a  way  to  access  the 
    instance.

     This is the Singleton pattern.




                                  
HOW ?

    Before release 1.5, there were two ways to 
    implement singletons. 
    Both are based on keeping the constructor 
    private and exporting a public static member to 
    provide access to the sole instance.
     In one approach, the member is a final field



                            
Singleton with public final field



    public class Elvis {
        public static final Elvis INSTANCE = new Elvis();
        private Elvis() { ... }
        public void leaveTheBuilding() { ... }
    }




                                      Reflexion!!!



                                 
Singleton with static factory

public class Elvis implements Serializable{
    private static final Elvis INSTANCE = new Elvis();
    private Elvis() {}
    public static Elvis getInstance() { 
              return INSTANCE; 
    }
}



                                  Serialisation!!!


                           
single­element enum type

    public enum Elvis {
        INSTANCE;
        public void leaveTheBuilding() { ... }
    }




                                    JAVA 5


                             
Lazy initialization

    Lazy initialization is the act of delaying the initialization 
    of a field until its value is needed.
    If the value is never needed, the field is never 
    initialized.
    Lazy initialization is a double­edged sword. It 
    decreases the cost of initializing a class or creating an 
    instance, at the expense of increasing the cost of 
    accessing the lazily initialized field.
    In the presence of multiple threads, lazy initialization is 
    tricky.
                                  
Lazy initialization of instance field
                synchronized accessor


    private static Elvis elvis;
    synchronized static  Elvis getElvis() {
        if (elvis == null)
            elvis = new Elvis();
        return elvis;
    }




                                   Slow!!!



                             
Double­Checked Locking idiom
                  DCL

static volatile Singleton instance;
public static Singleton getInstance() {
  if (instance == null) {
    synchronized (Singleton.class) {
      if (instance == null)
        instance == new Singleton();
    }
  }
  return instance;
}

                             No java 1.4!!!



                          
Lazy initialization holder class idiom


private static class ElvisHolder {
    static final Elvis INSTANCE = new Elvis();
}
static Elvis getInstance() { 
    return ElvisHolder.INSTANCE; 
}




                               JAVA 5 & 1.4


                         
References

    GoF
    Effective Java 1 & 2
    http://fr.wikipedia.org/wiki/Double­checked_locking




                                  

More Related Content

Similar to Singleton Sum

Singleton Pattern (Sole Object with Global Access)
Singleton Pattern (Sole Object with Global Access)Singleton Pattern (Sole Object with Global Access)
Singleton Pattern (Sole Object with Global Access)Sameer Rathoud
 
Kotlin what_you_need_to_know-converted event 4 with nigerians
Kotlin  what_you_need_to_know-converted event 4 with nigeriansKotlin  what_you_need_to_know-converted event 4 with nigerians
Kotlin what_you_need_to_know-converted event 4 with nigeriansjunaidhasan17
 
Day 2 Compose Camp.pptx
Day 2 Compose Camp.pptxDay 2 Compose Camp.pptx
Day 2 Compose Camp.pptxShayantaniKar
 
Singleton Pattern
Singleton PatternSingleton Pattern
Singleton PatternBorey Lim
 
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdfch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdfbca23189c
 
EESTEC Android Workshops - 101 Java, OOP and Introduction to Android
EESTEC Android Workshops - 101 Java, OOP and Introduction to AndroidEESTEC Android Workshops - 101 Java, OOP and Introduction to Android
EESTEC Android Workshops - 101 Java, OOP and Introduction to AndroidAntonis Kalipetis
 
Java Course 4: Exceptions & Collections
Java Course 4: Exceptions & CollectionsJava Course 4: Exceptions & Collections
Java Course 4: Exceptions & CollectionsAnton Keks
 
Java Serialization
Java SerializationJava Serialization
Java Serializationjeslie
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in javaAriful Islam
 
How would you implement multiple inheritance in java
How would you implement multiple inheritance in javaHow would you implement multiple inheritance in java
How would you implement multiple inheritance in javaTyagi2636
 
Java interview questions and answers for cognizant By Data Council Pune
Java interview questions and answers for cognizant By Data Council PuneJava interview questions and answers for cognizant By Data Council Pune
Java interview questions and answers for cognizant By Data Council PunePankaj kshirsagar
 
Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017Arsen Gasparyan
 
25 java interview questions
25 java interview questions25 java interview questions
25 java interview questionsMehtaacademy
 

Similar to Singleton Sum (20)

Singleton Pattern (Sole Object with Global Access)
Singleton Pattern (Sole Object with Global Access)Singleton Pattern (Sole Object with Global Access)
Singleton Pattern (Sole Object with Global Access)
 
Java training in delhi
Java training in delhiJava training in delhi
Java training in delhi
 
Core_java_ppt.ppt
Core_java_ppt.pptCore_java_ppt.ppt
Core_java_ppt.ppt
 
Kotlin what_you_need_to_know-converted event 4 with nigerians
Kotlin  what_you_need_to_know-converted event 4 with nigeriansKotlin  what_you_need_to_know-converted event 4 with nigerians
Kotlin what_you_need_to_know-converted event 4 with nigerians
 
Day 2 Compose Camp.pptx
Day 2 Compose Camp.pptxDay 2 Compose Camp.pptx
Day 2 Compose Camp.pptx
 
Singleton Pattern
Singleton PatternSingleton Pattern
Singleton Pattern
 
Singleton
SingletonSingleton
Singleton
 
Presentation to java
Presentation  to  javaPresentation  to  java
Presentation to java
 
Kotlin intro
Kotlin introKotlin intro
Kotlin intro
 
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdfch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
 
EESTEC Android Workshops - 101 Java, OOP and Introduction to Android
EESTEC Android Workshops - 101 Java, OOP and Introduction to AndroidEESTEC Android Workshops - 101 Java, OOP and Introduction to Android
EESTEC Android Workshops - 101 Java, OOP and Introduction to Android
 
Java
JavaJava
Java
 
Java Course 4: Exceptions & Collections
Java Course 4: Exceptions & CollectionsJava Course 4: Exceptions & Collections
Java Course 4: Exceptions & Collections
 
Java Serialization
Java SerializationJava Serialization
Java Serialization
 
core java
core javacore java
core java
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
How would you implement multiple inheritance in java
How would you implement multiple inheritance in javaHow would you implement multiple inheritance in java
How would you implement multiple inheritance in java
 
Java interview questions and answers for cognizant By Data Council Pune
Java interview questions and answers for cognizant By Data Council PuneJava interview questions and answers for cognizant By Data Council Pune
Java interview questions and answers for cognizant By Data Council Pune
 
Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017
 
25 java interview questions
25 java interview questions25 java interview questions
25 java interview questions
 

More from Slim Ouertani

More from Slim Ouertani (17)

merged_document_3
merged_document_3merged_document_3
merged_document_3
 
Microservice architecture
Microservice architectureMicroservice architecture
Microservice architecture
 
MongoDb java
MongoDb javaMongoDb java
MongoDb java
 
Effectuation: entrepreneurship for all
Effectuation: entrepreneurship for all Effectuation: entrepreneurship for all
Effectuation: entrepreneurship for all
 
Spring
SpringSpring
Spring
 
Principles of Reactive Programming
Principles of Reactive ProgrammingPrinciples of Reactive Programming
Principles of Reactive Programming
 
Functional Programming Principles in Scala
Functional Programming Principles in ScalaFunctional Programming Principles in Scala
Functional Programming Principles in Scala
 
Introduction to Cmmi for development
Introduction to Cmmi for development Introduction to Cmmi for development
Introduction to Cmmi for development
 
MongoDb java
MongoDb javaMongoDb java
MongoDb java
 
DBA MongoDb
DBA MongoDbDBA MongoDb
DBA MongoDb
 
SOA Trainer
SOA TrainerSOA Trainer
SOA Trainer
 
SOA Professional
SOA ProfessionalSOA Professional
SOA Professional
 
SOA Architect
SOA ArchitectSOA Architect
SOA Architect
 
PMP Score
PMP ScorePMP Score
PMP Score
 
PMP
PMPPMP
PMP
 
Programmation fonctionnelle Scala
Programmation fonctionnelle ScalaProgrammation fonctionnelle Scala
Programmation fonctionnelle Scala
 
Xml & Java
Xml & JavaXml & Java
Xml & Java
 

Recently uploaded

A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...apidays
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 

Recently uploaded (20)

A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 

Singleton Sum

  • 1. Singleton    Singleton pattern in java enterprise world Slim Ouertani    
  • 2. Intent Ensure a class only has one instance, and  provide a global point of access to it. [GoF p  119]    
  • 3. Motivation  It's important for some classes to have exactly one  instance. Although there can be many printers in a  system, there should be only one printer spooler.  How do we ensure that a class has only one instance  and that the instance is easily accessible?  A global variable makes an object accessible, but it  doesn't keep you from instantiating multiple objects.    
  • 4. Motivation A better solution is to make the class itself responsible  for keeping track of its sole instance.  The  class  can  ensure  that  no  other  instance  can  be  created  (by  intercepting  requests  to  create  new  objects),  and  it  can  provide  a  way  to  access  the  instance.  This is the Singleton pattern.    
  • 5. HOW ? Before release 1.5, there were two ways to  implement singletons.  Both are based on keeping the constructor  private and exporting a public static member to  provide access to the sole instance.  In one approach, the member is a final field    
  • 6. Singleton with public final field public class Elvis {     public static final Elvis INSTANCE = new Elvis();     private Elvis() { ... }     public void leaveTheBuilding() { ... } } Reflexion!!!    
  • 8. single­element enum type public enum Elvis {     INSTANCE;     public void leaveTheBuilding() { ... } } JAVA 5    
  • 9. Lazy initialization Lazy initialization is the act of delaying the initialization  of a field until its value is needed. If the value is never needed, the field is never  initialized. Lazy initialization is a double­edged sword. It  decreases the cost of initializing a class or creating an  instance, at the expense of increasing the cost of  accessing the lazily initialized field. In the presence of multiple threads, lazy initialization is  tricky.    
  • 10. Lazy initialization of instance field synchronized accessor private static Elvis elvis; synchronized static  Elvis getElvis() {     if (elvis == null)         elvis = new Elvis();     return elvis; } Slow!!!    
  • 11. Double­Checked Locking idiom DCL static volatile Singleton instance; public static Singleton getInstance() {   if (instance == null) {     synchronized (Singleton.class) {       if (instance == null)         instance == new Singleton();     }   }   return instance; } No java 1.4!!!    
  • 13. References GoF Effective Java 1 & 2 http://fr.wikipedia.org/wiki/Double­checked_locking