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

Slides:



Advertisements
Similar presentations
Chapter 5: The Singleton Pattern
Advertisements

Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
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:
Variable types We have already encountered the idea of a variable type. It is also possible to think about variables in terms of their kind, namely: 1)
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.
Road Map Introduction to object oriented programming. Classes
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 =
Terms and Rules Professor Evan Korth New York University (All rights reserved)
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.
Proxy Design Pattern Source: Design Patterns – Elements of Reusable Object- Oriented Software; Gamma, et. al.
Singleton Christopher Chiaverini Software Design & Documentation September 18, 2003.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
!!! Global Variables!!! are EVIL SSimply because you just write a school boy/gal?
Patterns in programming 1. What are patterns? “A design pattern is a general, reusable solution to a commonly occurring problem in software. A design.
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.
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.
The Singleton Pattern SE-2811 Dr. Mark L. Hornick 1.
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.
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 8, Class 3: Model-View-Controller Final Project Worth 2 labs Cleanup of Ducks Reducing coupling Finishing FactoryMethod Cleanup of Singleton SE-2811.
NETW 3005 Monitors and Deadlocks. Reading For this lecture, you should have read Chapter 7. NETW3005 (Operating Systems) Lecture 06 - Deadlocks2.
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
Multithreading / Concurrency
Phil Tayco Slide version 1.0 Created Sep 18, 2017
Multi Threading.
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
Abstract Factory Pattern
Singleton Pattern Command Pattern
Lecture 25 More Synchronized Data and Producer/Consumer Relationship
Specifying Multithreaded Java semantics for Program Verification
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….
Unit 3 Test: Friday.
CS 350 – Software Design Singleton – Chapter 21
Chapter 14 Abstract Classes and Interfaces
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

Sometimes it is important to have only one instance of a class One printer spooler (though many printers) One file system One window manager The challenge: Ensure that a certain class has only one instance Provide global access to it

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

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

Moving towards a solution… Restrict the ability to construct more than one instance of a Singleton class Make the class responsible for keeping track of its one and only instance 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 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. 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. Creating a Singleton object can be resource intensive and you may not want to create it until you need it. We might not have all the information to create an object at static initialization time. Example: the kind of file/database/resource that you are connecting to is usually not known at startup

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; static variable to hold the single instance of the class. Only this class can instantiate itself. 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 Value of uniqueInstance Singleton.getInstance() null if (uniqueInstance == null){ if (uniqueInstance == null) { uniqueInstance = new Singleton() Object 1 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) { uniqueInstance = new Singleton(); return uniqueInstance; volatile ensures that the JVM always has an up-to-date value of uniqueInstance Enter a synchronized block only when there is no instance. We need to synchronize only the first time through.

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

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.