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.

Slides:



Advertisements
Similar presentations
Chapter 5: The Singleton Pattern
Advertisements

Relaxed Consistency Models. Outline Lazy Release Consistency TreadMarks DSM system.
Concurrency 101 Shared state. Part 1: General Concepts 2.
Design Patterns CMPS Design Patterns Consider previous solutions to problems similar to any new problem ▫ must have some characteristics in common.
March Ron McFadyen1 Design Patterns In software engineering, a design pattern is a generally repeatable solution to a commonly-occurring problem.
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.
Nov R McFadyen1 Design Patterns (GoF) contains the creational patterns: Abstract factory Builder Factory method (section 23.3 has a Simple.
Threading Part 2 CS221 – 4/22/09. Where We Left Off Simple Threads Program: – Start a worker thread from the Main thread – Worker thread prints messages.
March R McFadyen1 Design Patterns (GoF) contains the creational patterns: Abstract factory Builder Factory method (in Larman) Prototype Singleton.
Chapter 15 Interaction Diagrams. Most Common Sequence Diagram Communication Diagram Sequence Diagrams illustrate interactions between classes of a program.
Winter 2007ACS-3913 Ron McFadyen1 Classes Represented by a rectangle with possibly 3 compartments Customer Name Address Customer Name Address getName()
March R McFadyen1 GoF (Gang of Four): Gamma, Johnson, Helm & Vlissides Book: Design Patterns: Elements of Reusable Object-Oriented Software.
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.
Oct Ron McFadyen Visibility Visibility: the ability of one object to see or have a reference to another object. e.g. When a register object.
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 =
1 Sharing Objects – Ch. 3 Visibility What is the source of the issue? Volatile Dekker’s algorithm Publication and Escape Thread Confinement Immutability.
March Ron McFadyen1 Singleton pattern Singleton is designed to restrict instantiation of a class to one (or a few) objects. Useful when exactly.
Concurrency Concurrency is the rule not the exception! e.g. M.S. Word responding to the keyboard, reformatting the document, making a backup copy, checking.
Design Patterns Ref : Chapter 15 Bennett et al. useful groups of collaborating classes that provide a solution to commonly occuring problems. provide.
1 Thread II Slides courtesy of Dr. Nilanjan Banerjee.
Chapter 5 - Writing a Problem Domain Class Definition1 Chapter 5 Writing a Problem Domain Class Definition.
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.
Systems Analysis and Design in a Changing World, 6th Edition
Threading and Concurrency Issues ● Creating Threads ● In Java ● Subclassing Thread ● Implementing Runnable ● Synchronization ● Immutable ● Synchronized.
Chapter 26 GoF Design Patterns. The Adapter Design Pattern.
In the name of Allah The Proxy Pattern Elham moazzen.
Starting Object Design
Optimistic Design 1. Guarded Methods Do something based on the fact that one or more objects have particular states  Make a set of purchases assuming.
Singleton and Basic UML CS340100, NTHU Yoshi. What is UML Unified Modeling Language A standardized general-purpose modeling language in the field of software.
2007ACS-3913 Ron McFadyen1 Class Diagram See Schaum’s UML Outline, especially chapters 4, 5, 6, 7.
SE-1010 Dr. Mark L. Hornick 1 Java Programming Basics.
1 More OO Design Patterns CSC 335: Object-Oriented Programming and Design.
The Singleton Pattern SE-2811 Dr. Mark L. Hornick 1.
Multiprocessor Cache Consistency (or, what does volatile mean?) Andrew Whitaker CSE451.
Singleton Duchenchuk Volodymyr Oksana Protsyk. 2 /48.
Design Patterns Introduction
Threads and Singleton. Threads  The JVM allows multiple “threads of execution”  Essentially separate programs running concurrently in one memory space.
1 Becoming More Effective with C++ … Day Two Stanley B. Lippman
Singleton Pattern Presented By:- Navaneet Kumar ise
The Singleton Pattern (Creational)
1 More OO Design Patterns CSC 335: Object-Oriented Programming and Design.
Java Coding 5 – Part 2 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. To object or not…
Singleton Pattern. Problem Want to ensure a single instance of a class, shared by all uses throughout a program Context Need to address initialization.
Chapter 7 Classes and Methods III: Static Methods and Variables Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition)
Specifying Multithreaded Java semantics for Program Verification Abhik Roychoudhury National University of Singapore (Joint work with Tulika Mitra)
Arc: Communications between Addins Dr Andy Evans.
M1G Introduction to Programming 2 2. Creating Classes: Game and Player.
1 Creational Design Patterns CSC 335: Object-Oriented Programming and Design.
Bjarne Stroustrup I have always wished that my computer would be as easy to use as my telephone. My wish has come true. I no longer know how to use my.
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.
Design Patterns – Chocolate Factory (from Head First Design Patterns)
The Singleton Pattern SE-2811 Dr. Mark L. Hornick.
Abstract Factory Pattern
Singleton Pattern Command Pattern
Design Patterns (GoF) contains the creational patterns:
Specifying Multithreaded Java semantics for Program Verification
Design Patterns in Operating Systems
Programming Design Patterns
SE-2811 Software Component Design
What is Singleton Category: Creational pattern
Singleton Pattern Pattern Name: Singleton Pattern Context
Singleton design pattern
CS 350 – Software Design Singleton – Chapter 21
SE-2811 Software Component Design
5. Strategy, Singleton Patterns
More concurrency issues
Presentation transcript:

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 uniqueInstance Static getInstance() uniqueInstance is a class variable that holds the one instance. getInstance() is a class method we can access regardless of whether there is an instance or not. Constructor is private. Chapter 5

Winter 2007ACS-3913 Ron McFadyen2 Singleton The text has a ChocolateBoiler class for which they want to have at most one instance. ChocolateBoiler private static ChocolateBoiler uniqueInstance; … private ChocolateBoiler() public static ChocolateBoiler getInstance() public void fill() public void drain() public void boil() public boolean isEmpty() public boolean isBoiled()

Winter 2007ACS-3913 Ron McFadyen3 Singleton In order to get a reference to the singleton object, the client object just sends the message: Singleton singleton = Singleton.getInstance(); One scenario: clientChocolateBoiler :ChocolateBoiler getInstance() fill()

Winter 2007ACS-3913 Ron McFadyen4 Singleton The other scenario: (when is this realized?) clientChocolateBoiler :ChocolateBoiler getInstance() fill()

Winter 2007ACS-3913 Ron McFadyen5 Singleton If there’s only ever one thread, the previous implementation will work. However, if there’s more than one thread we could end up with multiple “singletons” (see page 188) Each thread has its own “copy” of variables. The value of a variable could be “out-of-sync” with the main copy. We could have getInstance started by several threads. Each could test the value of uniqueInstance and proceed to instantiate the singleton. To work correctly, we need a technique to synchronize the actions of the threads. With Java we could use synchronization of methods or variables.

Winter 2007ACS-3913 Ron McFadyen6 Synchronized Methods The text suggests synchronized static methods as one solution. This results in locking and unlocking of the class, and hence only one synchronized method will execute at a time. public class Singleton { private static Singleton uniqueInstance; // other useful instance variables here private Singleton() {} public static synchronized Singleton getInstance() { if (uniqueInstance == null) { uniqueInstance = new Singleton(); } return uniqueInstance; } // other useful methods here }

Winter 2007ACS-3913 Ron McFadyen7 Synchronized Methods Synchronized methods introduce overhead and we can avoid them. Some alternatives, use: a)double-checked locking b)eager instantiation

Winter 2007ACS-3913 Ron McFadyen8 Double-checked locking Check first to see if the instance exists or not. If not, then lock up a block of code. // Danger! This implementation of Singleton not // guaranteed to work prior to Java 5 // public class Singleton { private volatile static Singleton uniqueInstance; private Singleton() {} public static Singleton getInstance() { if (uniqueInstance == null) { synchronized (Singleton.class) { if (uniqueInstance == null) { uniqueInstance = new Singleton(); } } } return uniqueInstance; } A synchronized block of code. Only one thread at a time will execute this. A thread’s copy of a volatile attribute is reconciled with the “master” copy each time it is referenced. Note these two checks on uniqueInstance Second check is necessary to verify uniqueInstance is still null Result is very little overhead compared to synchronizing a whole method/class. Oct 2008: ignore this slide

Winter 2007ACS-3913 Ron McFadyen9 Another alternative: Eager Instantiation If your system always instantiates the singleton, then create it in advance – very simple – done by class loader public class Singleton { private static Singleton uniqueInstance = new Singleton(); private Singleton() {} public static Singleton getInstance() { return uniqueInstance; } When asked, just return the reference to the static variable One instance as a class variable When the class is loaded, the instance is created and available. getInstance() is always realized the same way.

Winter 2007ACS-3913 Ron McFadyen10 Singleton How do we show that some class in a UML class diagram is a singleton class? How do we, in one UML sequence diagram, show how getInstance() can be realized (there are two possibilities) for the lazy instantiation variation of Singleton? (see Schaum’s UML Outline)