Singleton Object Management
-
Upload
ppd1961 -
Category
Technology
-
view
2.368 -
download
1
description
Transcript of Singleton Object Management
November 7, 2005
Singleton Object Management
Dr. Partha Pratim DasInterra Systems (India) Pvt. Ltd.
Resource Management Series
04/10/23 22
Agenda
• Backgrounder– atexit() behavior– Object Lifetime
• Singleton Class– What?, Why? & How?– A simple singleton
• How to enforce singleton discipline
– Meyer’s Singleton• The Dead Reference Problem
– The Phoenix Singleton
• Q&A
04/10/23 33
Backgrounder
Object Object LifetimeLifetime
04/10/23 44
atexit() Callback Behavior – Execute code after main()
• atexit() signatureint atexit(void (*pFunction)(void)); // 0 is success
• Use atexit() to register any function having the following signature
void CallbackFunction(void);
• The registered function will be called from the runtime system after main() exits
• If multiple functions are registered, then the calls will made be in the reverse order of registration (LIFO)
• Used by:– Compiler for
• Local Static Objects– Application Programmer for any function call beyond main()
04/10/23 55
atexit() Callback Behavior
• Note:– Executing return from main() or direct call
to exit(.) invokes all callbacks registered with atexit() before the control actually exits (global destructors are called).
– Call to abort() bypasses callbacks.– atexit() registration from within a Callback
function may have unspecified behavior.
04/10/23 66
Object Lifetime
• Starts with Constructor execution– Must follow Memory Allocation
• Ends with Destructor execution– Must precede Memory De-allocation
• For Built-in Types (w/o Constructor / Destructor) the notion follows the same pattern though the compiler actually optimizes the creation / destruction processes.
04/10/23 77
Object Lifetime
• Automatic Object – Function / Block Scope– Space allocated on stack when (just before) the control
enters the scope
– Object created (and initialized) when the control passes the declaration
– Object destroyed when (just after) the control leaves the scope
– Objects (within a scope) are destroyed in the reverse order of creations
– Space de-allocated after all automatic objects have been destructed.
04/10/23 88
Object Lifetime
• Non-static member Object – Class Scope– Constructed in the initialization list of the
Constructor of the Parent Object• Before the first statement of the constructor
executes
– Follows the lexical order of declarations in the class
– Destructed by the Destructor of the Parent Object
• After the last statement of the destructor executes
04/10/23 99
Object Lifetime
• Free Store Object– Lifetime controlled by the user– Constructor called by operator new
• Must follow Memory Allocation
– Destructor called by operator delete• Must precede Memory De-allocation
04/10/23 1010
Object Lifetime
• Static Object – Global / Class Scope– Built-in Type – no constructor / destructor
• Object created (and initialized) implicitly when the program is loaded
– before first assembly instruction in main()– actually before any global object of user-defined type is
constructed
• Object destroyed implicitly before the program is unloaded – after last assembly instruction in main()– actually after all global objects of user-defined type are
destructed
• Has no boundary for translation units – literally “load time”• Has no executable code in construction / destruction.
04/10/23 1111
Object Lifetime
• Static Object – Global / Class Scope– User-Defined Types
• Space allocation is done at “load-time”. • Allocated space is zero-filled• Object created (and initialized) sequentially within a
translation unit • Creation order between different translation units is arbitrary
– Some iostreams objects are properly initialized for use by the static constructors. These control text streams – cin, cout, cerr, clog
• Destroyed in the reverse order of creations – creation order is static
– iostreams objects can be used within the destructors called for static objects, during program termination.
04/10/23 1212
Object Lifetime
• Static Object – Function / Local Scope– Built-in Type
• Same as static objects in Global / Class Scope
– User-Defined Types• Object created (and initialized) when the control
passes the declaration for the first time• Destroyed in the reverse order of creations (LIFO)
– after last assembly instruction in main()– before the global objects of user-defined type are destructed
• Uses atexit() – because the creation order is dynamic
04/10/23 1313
Static Object Lifetime
An ExampleAn Example
13-May-05 1414
13-May-05 1515
13-May-05 1616
13-May-05 1717
11-Nov-05 1818
Output: VC 6.0Output: VC 6.0
11-Nov-05 1919
Output: VC 7.1Output: VC 7.1
04/10/23 2020
Singleton Objects
What and WhyWhat and Why
04/10/23 Source: Modern C++ Design 2121
What is a Singleton Class?
• A class is a singleton if– It has only one instance, and– Global point of access to the singular instance– Can be accessed anytime during the application
• “Global point of access” – Implications – Singleton object “owns” itself– No client step to create singletons– Creates and Destroys itself.
• Singleton is a Design Pattern• A singleton is an improved global variable
04/10/23 2222
Lifetime Semantics for a Singleton
• A single object of a class stays throughout the lifetime of an application – Created when the execution of the program “starts” and
remains there till the application “ends”
• The Singleton class is instantiated at the time of first access and same instance is used thereafter till the application quits.
• At no point during execution there is more than one instance of the class; but in between it may be created & destroyed several times.– There are execution points where no object exists.
04/10/23 2323
Singleton Examples
• The office of the President of India is a Singleton. – The constitution specifies the means by which a
President is selected, limits the term of office, and defines the order of succession.
– There can be at most one President at any given time.
– There will be exactly one at any given time.
– Regardless of the personal identity of the President, the title, “President of India" is a global point of access that identifies the person in the office.
04/10/23 2424
Singleton Examples
• Purify license in a network can be a Singleton. – A Singleton connection objects can ensure that only
one connection can be made at any time. • Printer can be a singleton in a network.• Keyboard, Display, Log, …• [MFC] – The global instance of the CWinApp-
derived application class is the singleton. • In EDAObjects™
– Memory Manager– Message Handler – Command Line Processor
04/10/23 2525
Singleton Implementation
HowHow
04/10/23 Source: Modern C++ Design 2626
Static Data + Static Function != Singleton
• Wrap the Singleton object and function that uses the object within a class
• Make both static• Keep the object private and the method
public• This is not a “good” singleton because
– static methods cannot be virtual– Initialization and Clean-up is difficult– There is no unique point of access
04/10/23 Source: Modern C++ Design 2727
Essence of Singleton Implementation
• To make a class singleton– Make all constructors private– Provide a static method as a unique access point
for the singleton.
• Examples follow …
13-May-05 2828
A Simple SingletonA Simple Singleton
04/10/23 Source: Modern C++ Design 2929
A Simple Singleton
• A simple – no-frills singleton is illustrated• Singleton is dynamically created
– a static creation may cause conflict in creation order
• Does not have a proper destruction point– Cannot delete from within main() since some
global objects may be using it
– Hence the singleton leaks• Is it a memory leak?
• Is it a resource leak?
04/10/23 Source: Modern C++ Design 3030
Meyer’s Singleton – A Solution
• Create the singleton as a local static object
• Will be destroyed at exit
• Does it solve all problems?
Singleton& Singleton::Instance() Singleton& Singleton::Instance() {{
static Singleton theInstance;static Singleton theInstance;return theInstance;return theInstance;
}}
04/10/23 Source: Modern C++ Design 3131
The Dead Reference Problem
• There are 3 singletons – – Keyboard, – Display and – Log
• Error Reporting
• Created on-demand
• All are implemented by Meyer’s Singleton
• Consider an exception scenario …
04/10/23 Source: Modern C++ Design 3232
The Dead Reference Scenario
• Keyboard successfully created • Display fails to initialize• Log created• Error logged; application proceeds to exit• Log destroyed (LIFO order)• Keyboard fails to shutdown• Log::Instance() invoked for error reporting
– Returns a dead object!!!
04/10/23 Source: Modern C++ Design 3333
The Dead Reference Detection
• Maintain a flag with every singleton that tells if the singleton is alive.
• If a dead reference is detected, an exceptions is raised.
• The code follows …
13-May-05 3434
Meyer’s Singleton with Dead Reference DetectionMeyer’s Singleton with Dead Reference Detection
04/10/23 Source: Modern C++ Design 3535
Phoenix Singleton
• Like Phoenix bird, this singleton rises repeatedly from its ashes
• Outline– Retrieve the Caracas (this a global allocation)– Reincarnate the singleton– Register a callback for destruction with atexit()
13-May-05 3636
Phoenix SingletonPhoenix Singleton
04/10/23 Source: Modern C++ Design 3737
More Singletons …
• Explicit Management of Lifetime with user-assigned priorities (Longevity Control)
• Singletons under multi-threading
• Singleton template
• Singletons in Java, C# and .NET
04/10/23 3838
Singletons in C++
References & CreditsReferences & Credits
04/10/23 3939
References: Books
• Modern C++ Design: Generic Programming & Design Pattern Applied by Andrei Alexandrescu, Pearson Education 2001
– Most of the material from “Implementing Singletons” chapter
• Exceptional C++ by Herb Sutter – Discussion on Object Lifetime
• Effective C++ & More Effective C++: by Scott Meyers– Many items relating to Object lifetime & Meyer’s Singleton
04/10/23 4040
References: Papers
• Object Lifetime Manager – A Complementary Pattern for Controlling Object Creation and Destruction by David L. Levine and Christopher D. Gill
Douglas C. Schmidt, Design Patterns in Communications, (Linda Rising, ed.), Cambridge University Press, 2000.
04/10/23 4141
Credits / Acknowledgements
• Debabrata Singha, ATOS Origin – discussion on the “Object Lifetime Manager”
paper.– understanding the atexit() behavior
04/10/23 4242
Thank You