November 7, 2005 Singleton Object Management Dr. Partha Pratim Das Interra Systems (India) Pvt. Ltd.   Resource Management Series
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
Backgrounder Object Lifetime
atexit()  Callback Behavior –  Execute code after  main() atexit()  signature int 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()
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.
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.
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.
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
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
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 .
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.
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
Static Object Lifetime An Example
 
 
 
 
Output: VC 6.0
Output: VC 7.1
Singleton Objects What and Why
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
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.
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.
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
Singleton Implementation How
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
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 …
A Simple Singleton
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?
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()  { static Singleton theInstance; return theInstance; }
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 …
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!!!
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 …
Meyer’s Singleton with Dead Reference Detection
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()
Phoenix Singleton
More Singletons … Explicit Management of Lifetime with user-assigned priorities (Longevity Control) Singletons under multi-threading Singleton template Singletons in Java, C# and .NET
Singletons in C++ References & Credits
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
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.
Credits / Acknowledgements Debabrata Singha, ATOS Origin  discussion on the “Object Lifetime Manager” paper. understanding the  atexit()  behavior
Thank You

Singleton Object Management

  • 1.
    November 7, 2005Singleton Object Management Dr. Partha Pratim Das Interra Systems (India) Pvt. Ltd. Resource Management Series
  • 2.
    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
  • 3.
  • 4.
    atexit() CallbackBehavior – Execute code after main() atexit() signature int 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()
  • 5.
    atexit() CallbackBehavior 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.
  • 6.
    Object Lifetime Startswith 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.
  • 7.
    Object Lifetime AutomaticObject – 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.
  • 8.
    Object Lifetime Non-staticmember 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
  • 9.
    Object Lifetime FreeStore 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
  • 10.
    Object Lifetime StaticObject – 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 .
  • 11.
    Object Lifetime StaticObject – 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.
  • 12.
    Object Lifetime StaticObject – 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
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
    What is aSingleton 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
  • 22.
    Lifetime Semantics fora 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.
  • 23.
    Singleton Examples Theoffice 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.
  • 24.
    Singleton Examples Purifylicense 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
  • 25.
  • 26.
    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
  • 27.
    Essence of SingletonImplementation To make a class singleton Make all constructors private Provide a static method as a unique access point for the singleton. Examples follow …
  • 28.
  • 29.
    A Simple SingletonA 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?
  • 30.
    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() { static Singleton theInstance; return theInstance; }
  • 31.
    The Dead ReferenceProblem There are 3 singletons – Keyboard, Display and Log Error Reporting Created on-demand All are implemented by Meyer’s Singleton Consider an exception scenario …
  • 32.
    The Dead ReferenceScenario 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!!!
  • 33.
    The Dead ReferenceDetection 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 …
  • 34.
    Meyer’s Singleton withDead Reference Detection
  • 35.
    Phoenix Singleton LikePhoenix 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()
  • 36.
  • 37.
    More Singletons …Explicit Management of Lifetime with user-assigned priorities (Longevity Control) Singletons under multi-threading Singleton template Singletons in Java, C# and .NET
  • 38.
    Singletons in C++References & Credits
  • 39.
    References: Books ModernC++ 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
  • 40.
    References: Papers ObjectLifetime 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.
  • 41.
    Credits / AcknowledgementsDebabrata Singha, ATOS Origin discussion on the “Object Lifetime Manager” paper. understanding the atexit() behavior
  • 42.