Design Patterns and Refactoring

Similar documents
Real Time Operating Systems

Real Time Operating Systems

public void run ( ) { i f ( this. id == 0) System. out. p r i n t ( 3 ) ; bro. j o i n ( ) ; else System. out. p r i n t ( 2 ) ;

Blocking Synchronization: Streams Vijay Saraswat (Dec 10, 2012)

SDS developer guide. Develop distributed and parallel applications in Java. Nathanaël Cottin. version

CS-206 Concurrency. Lecture 8 Concurrent. Data structures. a b c d. Spring 2015 Prof. Babak Falsafi parsa.epfl.ch/courses/cs206/ remove(c) remove(b)

Safety and Liveness. Thread Synchronization: Too Much Milk. Critical Sections. A Really Cool Theorem

INF Models of concurrency

Thread Specific Storage

Scheduling I. Today. Next Time. ! Introduction to scheduling! Classical algorithms. ! Advanced topics on scheduling

Queuing Networks. - Outline of queuing networks. - Mean Value Analisys (MVA) for open and closed queuing networks

CPU SCHEDULING RONG ZHENG

Lists, Stacks, and Queues (plus Priority Queues)

CS162 Operating Systems and Systems Programming Lecture 7 Semaphores, Conditional Variables, Deadlocks"

Maps performance tips On server: Maintain DB connections, prepared statements (per thread/request!)

Computer Science Introductory Course MSc - Introduction to Java

TDDB68 Concurrent programming and operating systems. Lecture: CPU Scheduling II

Che-Wei Chang Department of Computer Science and Information Engineering, Chang Gung University

1. Write a program to calculate distance traveled by light

More on Methods and Encapsulation

More About Methods. Hsuan-Tien Lin. Deptartment of CSIE, NTU. OOP Class, March 8-9, 2010

Sharing Objects. Pieter van den Hombergh. Fontys Hogeschool voor Techniek en Logistiek. February 15, 2017

Object Oriented Software Design (NTU, Class Even, Spring 2009) Final Examination Problem Sheet TIME: 06/16/2009, 14:20 17:20

Extensibility Patterns: Extension Access

Clojure Concurrency Constructs, Part Two. CSCI 5828: Foundations of Software Engineering Lecture 13 10/07/2014

Shared resources. Sistemi in tempo reale. Giuseppe Lipari. Scuola Superiore Sant Anna Pisa -Italy

Information System Design IT60105

Lecture 13. Real-Time Scheduling. Daniel Kästner AbsInt GmbH 2013

arxiv: v1 [cs.se] 10 Jan 2018

CEC 450 Real-Time Systems

PySy: A Python Package for Enhanced Concurrent Programming. TODD WILLIAMSON B.S (University of California at Davis) 2007 THESIS

CSE 380 Computer Operating Systems

Lecture 5: Sep. 23 &25

Scheduling I. Today Introduction to scheduling Classical algorithms. Next Time Advanced topics on scheduling

Techniques of Java Programming

Performance Analysis of Lattice QCD Application with APGAS Programming Model

From High-Level Component-Based Models to Distributed Implementations

Outline. PeerSim: Informal introduction. Resources. What is PeerSim? Alberto Montresor Gianluca Ciccarelli

Multicore Semantics and Programming

Distributed Systems Part II Solution to Exercise Sheet 10

Synchronous Reactive Systems

Real-Time Scheduling and Resource Management

From Sequential Circuits to Real Computers

Go Tutorial. Ian Lance Taylor. Introduction. Why? Language. Go Tutorial. Ian Lance Taylor. GCC Summit, October 27, 2010

CPU scheduling. CPU Scheduling

Distributed Algorithms Time, clocks and the ordering of events

Agreement. Today. l Coordination and agreement in group communication. l Consensus

Marwan Burelle. Parallel and Concurrent Programming. Introduction and Foundation

Applying Architectural Patterns for Parallel Programming Solving the One-dimensional Heat Equation

CHAPTER 5 - PROCESS SCHEDULING

13 Concurrent Programming using Tasks and Services

Embedded Systems Development

Tou has been released!

ITI Introduction to Computing II

Microcontroller VU

How to deal with uncertainties and dynamicity?

Deadlock (2) Dave Eckhardt Brian Railing Roger Dannenberg

Scheduling. Uwe R. Zimmer & Alistair Rendell The Australian National University

Socket Programming. Daniel Zappala. CS 360 Internet Programming Brigham Young University

INF Models of concurrency

Optimal strategies for maintaining a chain of relays between an explorer and a base camp

The conceptual view. by Gerrit Muller University of Southeast Norway-NISE

An object-oriented design process. Weather system description. Layered architecture. Process stages. System context and models of use

Chapter 7. Sequential Circuits Registers, Counters, RAM

IN4R21. Real-Time Specification for Java (RTSJ) Damien MASSON January 20, 2014

INF 4140: Models of Concurrency Series 3

CMSC 132, Object-Oriented Programming II Summer Lecture 12

COMPUTER SCIENCE TRIPOS

Imperative Data Parallelism (Correctness)

Basic Java OOP 10/12/2015. Department of Computer Science & Information Engineering. National Taiwan University

Lecture 11 Safety, Liveness, and Regular Expression Logics

A Spatial Data Infrastructure for Landslides and Floods in Italy

Administrivia. Course Objectives. Overview. Lecture Notes Week markem/cs333/ 2. Staff. 3. Prerequisites. 4. Grading. 1. Theory and application

Exercise 1 (15 points)

Lab Course: distributed data analytics

Distributed Architectures

Binding Performance and Power of Dense Linear Algebra Operations

Simulation & Modeling Event-Oriented Simulations

Real-Time Scheduling. Real Time Operating Systems and Middleware. Luca Abeni

Estimation of DNS Source and Cache Dynamics under Interval-Censored Age Sampling

Latches. October 13, 2003 Latches 1

Modern Functional Programming and Actors With Scala and Akka

ITI Introduction to Computing II

DMP. Deterministic Shared Memory Multiprocessing. Presenter: Wu, Weiyi Yale University

Behavioral Simulations in MapReduce

CMSC 132, Object-Oriented Programming II Summer Lecture 6:

CS 425 / ECE 428 Distributed Systems Fall Indranil Gupta (Indy) Oct. 5, 2017 Lecture 12: Time and Ordering All slides IG

Real-Time and Embedded Systems (M) Lecture 5

Announcements. John Jannotti (cs32) Design Patterns Feb 13, / 1

Operating Systems. VII. Synchronization

Multi-threading model

ECE 407 Computer Aided Design for Electronic Systems. Simulation. Instructor: Maria K. Michael. Overview

Exercise 1: Formal Tools and Techniques (10 points)

Voortgezet Programmeren

Concurrent HTTP Proxy Server. CS425 - Computer Networks Vaibhav Nagar(14785)

I/O Devices. Device. Lecture Notes Week 8

B629 project - StreamIt MPI Backend. Nilesh Mahajan

Class versus Instance (Section 5.1)

Discovering Spam On Twitter

Using Timed Input/Output Automata for Implementing Distributed Systems

Transcription:

Singleton Oliver Haase HTWG Konstanz 1 / 19

Description I Classification: object based creational pattern Puropse: ensure that a class can be instantiated exactly once provide global access point to single instance Application Examples: exactly one driver for a piece if hardware (e.g. printer) exactly one socket listener that receives incoming requests application that can be started only once global event queue for discrete event simulation 2 / 19

Description II Structure: Members: Singleton responsible for creation of the instance provides static operation for access to the instance Interactions: clients access singleton instance through getinstance operation 3 / 19

Description III Alternative: Class with static variables and static methods Drawbacks: 4 / 19

Description III Alternative: Class with static variables and static methods Drawbacks: Java interfaces cannot contain static methods class cannot be hidden behind interface each method invocation contains class name undermines polymorphism 4 / 19

5 / 19

Singleton implementation with Lazy Instantiation 1 public c l a s s MySingleton { 2 private s t a t i c MySingleton i n s t a n c e = n u l l ; 3 private MySingleton () { 4 5 6 public s t a t i c MySingleton g e t I n s t a n c e () { 7 i f ( i n s t a n c e == n u l l ) { 8 i n s t a n c e = new M y S i n g l e t o n ( ) ; 9 10 return instance ; 11 12 13 5 / 19

Singleton implementation with Lazy Instantiation 1 public c l a s s MySingleton { 2 private s t a t i c MySingleton i n s t a n c e = n u l l ; 3 private MySingleton () { 4 5 6 public s t a t i c MySingleton g e t I n s t a n c e () { 7 i f ( i n s t a n c e == n u l l ) { 8 i n s t a n c e = new M y S i n g l e t o n ( ) ; 9 10 return instance ; 11 12 13 Problem: Can lead to several instances if thread gets interrupted between lines 7 and 8 not thread-safe! 5 / 19

Resolve concurrency problem through synchronization: public c l a s s MySingleton { private s t a t i c MySingleton i n s t a n c e = n u l l ; private MySingleton () { public s t a t i c synchronized MySingleton g e t I n s t a n c e () { i f ( i n s t a n c e == n u l l ) { i n s t a n c e = new M y S i n g l e t o n ( ) ; return instance ; 6 / 19

Problem: Only first call of getinstance needs to be synchronized: unnecessary reduction of concurrency synchronized Methods always slower than unsynchronized methods: test program with 109 sequential getinstance calls on Mac Mini, 2 GHz Intel Core 2 Duo, 1 GB RAM, 120 GB hard drive: unsynchronized synchronized 4 sec. 58 sec. 7 / 19

with Checked Locking 1 public c l a s s MySingleton { 2 private s t a t i c MySingleton i n s t a n c e = n u l l ; 3 private MySingleton () { 4 5 6 public s t a t i c MySingleton g e t I n s t a n c e () { 7 i f ( i n s t a n c e == n u l l ) { 8 synchronized ( MySingleton. c l a s s ) { 9 i n s t a n c e = new M y S i n g l e t o n ( ) ; 10 11 12 return instance ; 13 14 15 8 / 19

Scenario: Thread1 gets interrupted between lines 8 and 9 holds monitor of MySingleton class object, no singleton instance created yet. Thread2 passes 7, waits at 8 for Thread1 Thread1 finishes, creates singleton instance Thread2 finishes, creates second singleton instance not thread-safe! 9 / 19

Solution attempt using Double-Checked-Locking-(Anti-)Pattern: 1 public c l a s s MySingleton { 2 private s t a t i c MySingleton i n s t a n c e = n u l l ; 3 private MySingleton () { 4 5 6 public s t a t i c MySingleton g e t I n s t a n c e () { 7 i f ( i n s t a n c e == n u l l ) { 8 synchronized ( MySingleton. c l a s s ) { 9 i f ( i n s t a n c e == n u l l ) { 10 i n s t a n c e = new M y S i n g l e t o n ( ) ; 11 12 13 14 return instance ; 15 16 17 Works well or does it? 10 / 19

Problem: Thread scheduling happens on the level of byte code, not on the Java source code level... object creation in line 10 i n s t a n c e = new M y S i n g l e t o n ( ) ; is mapped to the following pseudo byte code 1 ptrmemory = a l l o c a t e M e m o r y ( ) 2 a s s i g n M e m o r y ( i n s t a n c e, ptrmemory ) 3 callmysingletonconstructor ( instance ) If scheduling takes place between lines 2 and 3 then instance!= null, even though instance has not been properly initialized Thread2 might return uninitialized object instance, if thread 10 is interrupted within line 10! 11 / 19

The simple things are often the best or: Life can be that simple! fully functional, performant solution: public c l a s s MySingleton { p r i v a t e s t a t i c M y S i n g l e t o n i n s t a n c e = new M y S i n g l e t o n ( ) ; private MySingleton () { public s t a t i c MySingleton g e t I n s t a n c e () { return instance ; 12 / 19

Consequences of the simple implementation 13 / 19

Consequences of the simple implementation Singleton instance is created (exactly once) at class loading time even if it will never be used but: this rarely happens because class loading is usually triggered by usage rather small damage Time consumption at loading rsther than at first usage neither better nor worse, only different... potential drawback: class loading order hardly predictable Problem, if one singleton instance is needed to create another 13 / 19

Usage Joi 1 programming language supports singleton pattern: s i n g l e t o n component MyComponent p r o v i d e s M y I n t e r f a c e { The current Joi implementation maps the Joi code to corresponding Java code. Reason: Joi doesn t support static class members static variables are modelled as members of a singleton class frequent usage of the singleton pattern Java Webstart: Technology for the dynamic download, execution and updating of applications 1 more informationen at http://www-home.htwg-konstanz.de/ haase/hp/joi.html and in [von Drachenfels, Haase, Walter. Joi - eine Java Spracherweiterung zur Reduzierung von Codeabha ngigkeiten. In HTWG Forum, 2008/2009] 14 / 19

Singleton Additional Considerations Sometimes, a singleton object needs to be configured at creation time (or at the time of first usage) Example: Socket listener that needs to listen on certain port Possible Realizations: add parameters to getinstance method: p u b l i c c l a s s CS1 { p r i v a t e s t a t i c CS1 i n s t a n c e = new CS1 ( ) ; private int state ; p r i v a t e CS1 ( ) { private void config ( int state ) { this. state = state ; p u b l i c s t a t i c CS1 g e t I n s t a n c e ( i n t s t a t e ) { instance. config ( state ); return instance ; params need to be passed into all subsequent getinstance calls 15 / 19

Singleton Additional Considerations two overloaded getinstance methods with and w/o parameters p u b l i c c l a s s CS2 { p r i v a t e s t a t i c CS2 i n s t a n c e = new CS1 ( ) ; private int state ; p r i v a t e CS2 ( ) { private void c o n f i g ( i n t s t a t e ) { this. state = state ; p u b l i c s t a t i c CS2 g e t I n s t a n c e ( i n t s t a t e ) { instance. config ( state ); return instance ; p u b l i c s t a t i c CS2 g e t I n s t a n c e ( ) { return instance ; 16 / 19

Singleton Additional Considerations getinstance method without params + separate config method; catch repeated config invocations p u b l i c c l a s s CS3 { p r i v a t e s t a t i c CS3 i n s t a n c e = new CS3 ( ) ; private int state ; p r i v a t e boolean c o n f i g u r e d = f a l s e ; p r i v a t e CS3 ( ) { public synchronized void c o n f i g ( i n t s t a t e ) throws E x c e p t i o n { i f ( configured ) throw new E x c e p t i o n ( a l r e a d y c o n f i g u r e d ) ; this. state = state ; t h i s. configured = true ; p u b l i c s t a t i c CS3 g e t I n s t a n c e ( ) { return instance ; 17 / 19

Singleton Additional Considerations getinstance method without params + separate static config method, catch repeated and/or missing config invocations p u b l i c c l a s s CS4 { p r i v a t e s t a t i c CS4 i n s t a n c e = new CS4 ( ) ; private int state ; p r i v a t e s t a t i c bo ole an c o n f i g u r e d = f a l s e ; p r i v a t e CS4 ( ) { 18 / 19

Singleton Additional Considerations public s t a t i c synchronized void c o n f i g ( i n t s t a t e ) throws E x c e p t i o n { i f ( configured ) { throw new E x c e p t i o n ( a l r e a d y c o n f i g u r e d ) ; instance. state = state ; configured = true ; p u b l i c s t a t i c CS4 g e t I n s t a n c e ( ) throws E x c e p t i o n { i f (! configured ) throw new E x c e p t i o n ( n o t c o n f i g u r e d y e t ) ; return instance ; 19 / 19