The Singleton Pattern SE-2811 Dr. Mark L. Hornick 1.

Slides:



Advertisements
Similar presentations
Chapter 5: The Singleton Pattern
Advertisements

Concurrency 101 Shared state. Part 1: General Concepts 2.
Week 9, Class 3: Model-View-Controller Final Project Worth 2 labs Happens-Before ( SE-2811 Slide design: Dr. Mark L. Hornick Content: Dr. Hornick Errors:
Jan Ron McFadyen1 Singleton To guarantee that there is at most one instance of a class we can apply the singleton pattern. Singleton Static.
Oct Ron McFadyen1 Singleton To guarantee that there is at most one instance of a class we can apply the singleton pattern. Singleton Static.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Spring 2010ACS-3913 Ron McFadyen1 Singleton To guarantee that there is at most one instance of a class we can apply the singleton pattern. Singleton Static.
Fall 2009ACS-3913 R McFadyen1 Singleton Problem: Exactly one instance of a certain object is required (this object is called a singleton). We must ensure.
1 Scenario: Audio Clip Imagine that your application played an audio clip Based on user action, a different audio clip may begin playing You want only.
1 What is the “volatile” Keyword? You can skip locking (thread synchronization) in some cases by using the volatile variables. –No locking/unlocking =
Static members Based on Java tutorial by Oracle: svars.html
Winter 2007ACS-3913 Ron McFadyen1 Singleton To guarantee that there is at most one instance of a class we can apply the singleton pattern. Singleton Static.
CREATIONAL DESIGN PATTERN Object Pool. CREATIONAL DESIGN PATTERN creational design patterns are design patterns that deal with object creation mechanisms,
Proxy Design Pattern Source: Design Patterns – Elements of Reusable Object- Oriented Software; Gamma, et. al.
Singleton Christopher Chiaverini Software Design & Documentation September 18, 2003.
1 Thread II Slides courtesy of Dr. Nilanjan Banerjee.
Design patterns. What is a design pattern? Christopher Alexander: «The pattern describes a problem which again and again occurs in the work, as well as.
!!! Global Variables!!! are EVIL SSimply because you just write a school boy/gal?
SOEN 6011 Software Engineering Processes Section SS Fall 2007 Dr Greg Butler
Patterns in programming 1. What are patterns? “A design pattern is a general, reusable solution to a commonly occurring problem in software. A design.
Software Engineering Design Patterns. Singleton Single instance of class Constructor is private static final Class instance constructed when application.
The Factory Patterns SE-2811 Dr. Mark L. Hornick 1.
Design Patterns CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns.
Singleton and Basic UML CS340100, NTHU Yoshi. What is UML Unified Modeling Language A standardized general-purpose modeling language in the field of software.
Patterns in programming1. 2 What are patterns? Answers to common design problems. A language used by developers –To discuss answers to design problems.
11/18/20151 Operating Systems Design (CS 423) Elsa L Gunter 2112 SC, UIUC Based on slides by Roy Campbell, Sam.
Design Patterns Singleton & Factory Pattern Eriq Muhammad Adams J. Mail : | Blog :
1 More OO Design Patterns CSC 335: Object-Oriented Programming and Design.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Week 3, Day 2: Threads Questions about Threads “Multithreading” in Swing Lab tomorrow: Quiz Lab 3: Threading! SE-2811 Slide design: Dr. Mark L. Hornick.
15.1 Threads and Multi- threading Understanding threads and multi-threading In general, modern computers perform one task at a time It is often.
COMPSCI 230 S2C 2015 Software Design and Construction Synchronization (cont.) Lecture 4 of Theme C.
Classes. Constructor A constructor is a special method whose purpose is to construct and initialize objects. Constructor name must be the same as the.
Singleton Duchenchuk Volodymyr Oksana Protsyk. 2 /48.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
Design Patterns SE464 Derek Rayside images from NetObjectives.com & Wikipedia.
Threads and Singleton. Threads  The JVM allows multiple “threads of execution”  Essentially separate programs running concurrently in one memory space.
Singleton Pattern Presented By:- Navaneet Kumar ise
The Singleton Pattern (Creational)
1 More OO Design Patterns CSC 335: Object-Oriented Programming and Design.
Singleton Pattern. Problem Want to ensure a single instance of a class, shared by all uses throughout a program Context Need to address initialization.
Week 9, Class 3: Java’s Happens-Before Memory Model (Slides used and skipped in class) SE-2811 Slide design: Dr. Mark L. Hornick Content: Dr. Hornick Errors:
1 Creational Design Patterns CSC 335: Object-Oriented Programming and Design.
5.1 Basics of defining and using classes A review of class and object definitions A class is a template or blueprint for an object A class defines.
Week 10, Day 3 Review for the quarter SE-2811 Slide design: Dr. Mark L. Hornick Content: Dr. Hornick Errors: Dr. Yoder 1.
1 Creational Design Patterns CSC 335: Object-Oriented Programming and Design.
Sun Proprietary/Confidential: Internal Use Only 1 Multi-Threading Primer Byron Nevins December 10, 2007.
Patterns in programming
Slide design: Dr. Mark L. Hornick
Slide design: Dr. Mark L. Hornick
Design Patterns – Chocolate Factory (from Head First Design Patterns)
Best Practices and Architecture
The Singleton Pattern SE-2811 Dr. Mark L. Hornick.
Abstract Factory Pattern
Singleton Pattern Command Pattern
Design Patterns in Operating Systems
Week 6, Class 2: Observer Pattern
Programming Design Patterns
SE-2811 Software Component Design
What is Singleton Category: Creational pattern
Singleton Pattern Pattern Name: Singleton Pattern Context
Singleton design pattern
Singleton …there can be only one….
CS 350 – Software Design Singleton – Chapter 21
SE-2811 Software Component Design
Design pattern Lecture 6.
Slide design: Dr. Mark L. Hornick
5. Strategy, Singleton Patterns
Creating and Using Classes
More concurrency issues
Presentation transcript:

The Singleton Pattern SE-2811 Dr. Mark L. Hornick 1

Sometimes it is important to have only one instance of a class One factory (that creates many “product” instances) One window manager One event logger The challenge: Ensure that a certain class has only one instance Provide global access to it

Question: How can you prevent any instances of a class from being created? SE-2811 Dr. Mark L. Hornick 3

Question: How can you prevent any instances of a class from being created? 1. Don’t write it… 2. ? SE-2811 Dr. Mark L. Hornick 4

Moving towards a solution… 1. Restrict the ability to construct more than one instance of a Singleton class 2. Make the class responsible for keeping track of its one and only instance 3. Provide a global (static) access method

Solution 1: Eager Instantiation using static initialization public class Singleton { private static Singleton uniqueInstance = new Singleton(); // private constructor cannot be called; // no instances can be created. private Singleton() { } // return the same instance to all callers of this method public static Singleton getInstance() { return uniqueInstance; }

Important Concepts 1. Why is the constructor private? Any client that tries to instantiate the Singleton class directly will get an error at compile time. This ensures that nobody other than the Singleton class and instantiate the object of this class. 2. How can you access the single instance of the Singleton class? getInstance() is a static method. We can use the class name to reference the method. Singleton.getInstance() This is how we can provide global access to the single instance of the Singleton class.

Eager instantiation has pros and cons Static initialization is guaranteed to be thread-safe Global/static objects are created whether they are used or not, as soon as the application is loaded. Even before the main() method is called! Creating a Singleton object can be resource intensive and you may not want to create it until you need it. Example: the object establishes a network connection to a remote database server upon creation We might not have all the information to create an object at static initialization time. Example: the specific file/database/resource that you are connecting to may not be known at application load time

Solution 2: A Lazy Singleton public class Singleton { private static Singleton uniqueInstance = null; private Singleton() { // construction code goes here. } public static Singleton getInstance() { if (uniqueInstance == null) { uniqueInstance = new Singleton(); } return uniqueInstance; } Only this class can instantiate itself. static variable to hold the single instance of the class. Provides a way to instantiate the class and also provides global access to it.

Lazy initialization The Singleton class on the previous slide uses lazy initialization The uniqueInstance is not created and stored in the getInstance() method until it is first accessed. public class Singleton { private static Singleton uniqueInstance = null;... public static Singleton getInstance() { if (uniqueInstance == null) { uniqueInstance = new Singleton(); } return uniqueInstance; }... }

Lazy Singletons can have issues with Multithreading Thread1Thread2Value of uniqueInstance Singleton.getInstance()null Singleton.getInstance()null if (uniqueInstance == null){null if (uniqueInstance == null) {null uniqueInstance = new Singleton() Object 1 return uniqueInstance;Object 1 uniqueInstance = new Singleton() Object 2 return uniqueInstance;Object 2

Another alternative for lazy initialization public class Singleton { private static volatile Singleton uniqueInstance = null; private Singleton() { // construction code goes here. } public static synchronized Singleton getInstance(){ if (uniqueInstance == null) { uniqueInstance = new Singleton(); } return uniqueInstance; } Using the Java keyword synchronized forces every thread to wait its turn before it can enter the method. This prevents two threads from entering the method at the same time.

The Cost of Synchronization Synchronization is expensive. Synchronized methods can take 100 times longer to execute than unsynchronized methods This can affect performance of your program if getInstance () is called frequently Synchronization is relevant only the first time though the method, so why force repeated usage? Once we have set the uniqueInstance to an appropriate instance, then there is no need to further synchronize the method.

Lazy Initialization Solution 2: Double-checked Locking public class Singleton { private volatile static Singleton uniqueInstance = null; private Singleton() { // construction code goes here. } public static Singleton getInstance() { if (uniqueInstance == null) { synchronized (Singleton.class) { if (uniqueInstance == null) { uniqueInstance = new Singleton(); } return uniqueInstance; } Enter a synchronized block only when there is no instance. We need to synchronize only the first time through. volatile ensures that the JVM always has an up-to-date value of uniqueInstance

Double-checked locking solves multithreading problems Thread1Thread2Value of uniqueInstance Singleton.getInstance()null Singleton.getInstance()null if (uniqueInstance == null)null if (uniqueInstance == null)null synchronized (Singleton.class) { if (uniqueInstance == null) uniqueInstance = new Singleton() } Object 1 return uniqueInstance; Object 1 synchronized (Singleton.class) { If (uniqueInstance == null) // will evaluate to false!!! Object 1 return uniqueInstance; Object 1

The Cost of Double-checked locking Code is more complex Additional complexity = decreased maintainability Is it worth it?

One final possible approach public class Singleton { public static Singleton uniqueInstance = new Singleton(); private Singleton() { // do nothing here. } Public static variable holds the single instance of the class. What’s wrong with this approach using an eager “global” variable?

Summary Lazy versus Eager instantiation With a Lazy Singleton, you do not have to create an instance until you need it. With Eager initialization, the object is created at load time, before it is actually needed And whether or not it is actually ever accessed A Singleton class encapsulates its sole instance. Singleton provides only one instance of a class and global access. Public global variables provide only global access but cannot ensure one and only one unique instance.