Oct 200592.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.
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.
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.
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.
Design Patterns Ref : Chapter 15 Bennett et al. useful groups of collaborating classes that provide a solution to commonly occuring problems. provide.
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.
1 Thread II Slides courtesy of Dr. Nilanjan Banerjee.
Test Automation For Web-Based Applications Portnov Computer School Presenter: Ellie Skobel.
Threading and Concurrency Issues ● Creating Threads ● In Java ● Subclassing Thread ● Implementing Runnable ● Synchronization ● Immutable ● Synchronized.
In the name of Allah The Proxy Pattern Elham moazzen.
Computer Science 313 – Advanced Programming Topics.
1 Web Based Programming Section 8 James King 12 August 2003.
Starting Object Design
Constructors CMSC 202. Object Creation Objects are created by using the operator new in statements such as… The following expression invokes a special.
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.
Internet Software Development Controlling Threads Paul J Krause.
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.
Java - Classes JPatterson. What is a class? public class _Alpha { public static void main(String [] args) { } You have been using classes all year – you.
Java Thread and Memory Model
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
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.
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.
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.
This In Java, the keyword this allows an object to refer to itself. Or, in other words, this refers to the current object – the object whose method or.
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
Agenda Warmup AP Exam Review: Litvin A2
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
Singleton …there can be only one….
CS 350 – Software Design Singleton – Chapter 21
SE-2811 Software Component Design
5. Strategy, Singleton Patterns
More concurrency issues
Presentation transcript:

Oct 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.

Oct 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()

Oct 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()

Oct Ron McFadyen4 Singleton The other scenario: clientChocolateBoiler :ChocolateBoiler getInstance() fill()

Oct 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.

Oct 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 }

Oct Ron McFadyen7 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. Why is the overhead less?

Oct Ron McFadyen8 Another alternative: Eager Instantiation If your system always instantiates the singleton, then create it in advance – very simple – done by class loader Eager vs Lazy Instantiation. 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