5 constructs: c++implicit singletons

#1 most implicit singleton in c++ is the ubiquitous “file-scope variable”. Extremely common in my projects.

  • — The constructs below are less implicit as they all use some explicit keyword to highlight the programmer’s intent
  • keyword “extern” — file-scope variable with extern
    • I seldom need it and don’t feel the need to remember the the details.. see other blogposts
  • keyword “static” — file-scope static variables
  • keyword “static” within function body — local static variables — have nice feature of predictable timing of initializaiton
  • keyword “static” within a class declaration —  static field

~~~~~~  The above are the 5 implicit singleton constructs ~~~~~~

Aha — it’s useful to recognize that when a data type is instantiated many many times i.e. non-singleton usage, it is usually part of a collection, or a local (stack) variable.

Sometimes we have the ambiguous situation where we use one of the constructs above, but we instantiate multiple instances of the class. It’s best to document the purpose like “instance1 for …; instance2 for …”

create more semi-singletons

In numerous legacy java codebases I worked with, many important methods are non-static methods but their usage suggest they should be static. Static methods can be used without (somehow) getting a handle on a host object. Note “getting” can be very complicated.

This complicates refactoring and testing.

Solution – create singletons in those host classes, but not strict singletons as in java. I call it “semi-singleton” where “semi” is like semi-conscious and semi-conductor.

java singleton^immutable classes #enum

In c++ (and perhaps java) Most singletons are designed as “casual singletons” i.e. they are used as singletons, can be instantiated twice if you really want to, although there’s seldom a good justification.

[[effJava]] explains that an immutable class needs no copying. I think this is a performance view. (Does it apply to Optional.java? )

However, we don’t need to work hard trying to make it strict singletons.  Strict singleton is a functional requirement i.e. 2nd instance would be a functional defect.

If an immutable class happens to be used as one-instance data type, then lucky. But tomorrow it may get instantiated twice.. no worries 🙂

If boss asks you to make this class singleton, you should point out the legwork required and the numerous loopholes to fix before achieving that goal. Worthwhile?

Java enum types are special. JVM guarantees them to be immutable AND singleton, even in the face of serialization. See P 311.

lazy singleton based@JVM dynamic classloading #Lea

In [[DougLea]] P86, this JVM expert pointed out that a simple “eager” singleton is eager in other language, but lazy in Java due to runtime on-demand class loading.

Specifically we mean a public[1] static final field. This initialization is thread-safe by default. Assuming the field is immediately accessed after class loading, this simple design is comparable to the familiar synchronized lazy singleton. What are the pros and cons?

Synchronized singleton requires more legwork (by developer) but
* It lets you pass computed ctor parameters at runtime. Note the singleton ctor is private but yo can call getInstance(userInput).
* As hinted earlier, if you load the class but do not immediately use the instance, then the simple design incurs the expensive initialization cost too early.

[[DougLea]] was writen before java5. With java5, [[EffJava]] advocates enum.

[1] DougLea actually prefers private field with public getter, for encapsulation.

concurrent lazy singleton using static-local var#c++

As explained in another blog post, static local is a shared mutable, but fortunately initialization is thread-safe:

“If multiple threads attempt to initialize the same static local variable concurrently, the initialization occurs exactly once (similar behavior can be obtained for arbitrary functions with std::call_once).” — https://en.cppreference.com/w/cpp/language/storage_duration

https://stackoverflow.com/questions/26013650/threadsafe-lazy-initialization-static-vs-stdcall-once-vs-double-checked-locki has 20 upvotes and looks substantiated. It also considers double-checking, std::call_once, atomics, CAS…

GCC uses platform-specific tricks to ensure a static local variable is initialized only once, on first use. 

Conclusion — On GCC and other compilers, this is the easiest solution for a concurrent lazy singleton.


c# static class emulated in java/c++ #all-static


use a (possibly nested) namespace to group related free functions. See google style guide.

c# has static classes. C++ offers something similar — P120 effC++. It’s a struct containing static fields. You are free to create multiple instances of this struct, but there’s just one copy for each field object. Kind of alternative design for a singleton.

This simulates a namespace.


In [[DougLea]] P86, this foremost OO expert briefly noted that it can be best practice to replace a java singleton with an all-static class

–c# is the most avant-garde on this front

  • C# static class can be stateful but rarely are
  • it can have a private ctor

python class^module(singleton)

Both modu5 and class2 are based on a idic. Both can contain “system-wide” i.e. global variables, effectively singleton objects.

A module is like a singleton class, without constructor or inheritance.

Global variables and singletons — I figured these out because 2nd time you import a module, the module-level objects aren’t created again! You can safely construct objects at the module level and all of them become global variables. Is this similar to c++ namespace variables?

Calling a method on a class goes through __getattr__ hook. Probably no such thing in a module?

Importing a regular module actually executes the *.py file – no such feature with a class.

Modules (not classes) are hooked into the (non-trivial) import mechanism.

Module functions vs Methods have differences. All module-level methods are like classmethods, so a module can be simpler to use if you want a simple singleton class.

See also

2 simple yet concurrent singleton implementations ] c++

Both designs are thread-safe.

  1. First design is the static factory method + a static data member initialization.
  2. Second design uses a local static object, based on [[eff C++]] P 222.
template<class T>
class StaticFieldSingleton {
 static StaticFieldSingleton<T> instance_; //declaration of static field
 StaticFieldSingleton() {
  cout << "StaticFieldSingleton() ctor\n";
 StaticFieldSingleton(StaticFieldSingleton<T> const &);
 StaticFieldSingleton<T>& operator=(StaticFieldSingleton<T> const &);
 static StaticFieldSingleton<T>& getInstance() {
  return instance_;
//separate definition required on any static field
template<class T> StaticFieldSingleton<t> StaticFieldSingleton<t>
::instance_; //<---def of static field: required complexity

///////////// 2nd design uses a static local object
class SimpleSingleton {
 SimpleSingleton() {
  cout << "SimpleSingleton()\n";
 SimpleSingleton(SimpleSingleton const &);
 SimpleSingleton& operator=(SimpleSingleton const &);
 static SimpleSingleton& get_instance() {
  static SimpleSingleton instance;//<----- cleaner syntax
  return instance;
int main() {

 SimpleSingleton& ins1 = SimpleSingleton::get_instance();
 SimpleSingleton& ins2 = SimpleSingleton::get_instance();
 cout << &ins1 << endl;
 cout << &ins2 << endl;


c# enum is more like c++ or java@@

I told a c++ veteran that c# enum is more like c++ and less like java enum (singleton-based). He felt the other way. He points out that each c# enum has rich metadata, attributes, reflection, and even a few methods (from System.Object). Also, each enum type is a distinct type in the type system, which is important to reflection. You can use extension methods to add functionality specific to a particular enum type.

I now feel here’s the root of the issue — c# added lots of convenience features to simple value types like integer and float. A c# enum is fundamentally a special integer type. Passed by value, it behaves like a simple integer.

So my soundbyte is, if c++ enum is a plain integer, then c# enum is an integer enriched with convenience features.

Compared to java — java enums have real OO features, but c# enums get the features by other means.

VBA ≅ javascript on a webpage (Singletons)

Let’s focus on the typical use cases —

* A typical javascript app Operates on a DOM tree of the enclosing webpage.
* A typical VBA app operates on the EOM tree (Excel object model) of an attached workbook.

—-} In both scenarios, the programmer’s Main job is manipulation of the objects in the *OM. The *OM tree is essentially a big family of singletons. I’d say most GUI apps rely heavily on singletons even if you don’t like singletons.

Usually the VBA app is tailor made for that particular workbook. Tight coupling between the workbook and the VBA module. Javascript is similar.

static object initialization order #lazy singletons

Java’s lazy singleton has a close relative among C++ idioms, comparable in popularity and implementation.

Basically, local statics are initialized upon first use, exactly. Other static Objects are initialized “sometime” before main() starts. See the Item on c vs c++ in [[More eff c++]] and P222 [[EffC++]].

In real life, this’s hard to control — a known problem but with standard solutions — something like a lazy singleton. See P 170 C++FAQ. Also addressed in [[EffC++]] P221.

java singleton – y nested class implementation important

http://en.wikipedia.org/wiki/Initialization_on_demand_holder_idiom is the recommended solution. My friend Rohan pointed out why this solution is sometimes necessary.

Say you can’t eagerly init the static field because it must wait for some service object.

Say you also don’t want to incur the static synchronization every time. Though un-contended lock acquisition is cheap, it’s never free.

singleton Q&&A — somewhat contrived

Some answers are found in http://www.javaworld.com/javaworld/jw-01-2001/jw-0112-singleton.html

q: why not just use a static var?
a: see the article

q: name 2 ways to end up with multiple singletons
a: see the article
A: deserialize
A: reflection

Q: lock-free lazy singleton?
A: http://en.wikipedia.org/wiki/Initialization_on_demand_holder_idiom

Q: is there no way to subclass a singleton class?

What if i create a nested class inside the singleton? Yes i modify its source code but keeping the private constructor private. Will i get away with an anon inner class that extends the singleton host class?

Q: is it one instance per class loader in a given JVM? Consider eager singleton.
A: i think so

Q: how about lazy singleton?
A: same thing. one instance per class loader.

subverting java private constructor #some c++

Private constructor is not watertight. Among the consequences, singletons must be carefully examined.

  • reflection
  • ObjectInputStream.readObject() — see other posts
  • de-serialization can instantiate the class without constructors (or field initializers).
    • RMI, EJB, JMS, Web service all use serialization
    • any time we copy an object across 2 jvm processes
  • if you see a private constructor, don’t feel safe — the class may be a nested class. In that case the enclosing class can call the private constructor. Worse still, another nested class (sister class) can also call the private constructor. And enclosed classes too. In summary all of these classes can call my private ctor —
    • ** my enclosing class
    • ** my “sister” classes ie other classes enclosed by my enclosing class
    • ** my “children” ie enclosed class including anonymous classes
    • ** my “grand-children” classes

— in c++

  • Friend function and friend class can call my private ctor.
    • Factory as friend
  • static method is frequently used by singletons

singletons complicate unit tests@@

http://code.google.com/p/google-singleton-detector/wiki/WhySingletonsAreControversial gave 2+1 /indictments/ against singletons in general. The first indictment is testability.

Not easy to introduce a mock/stub for the singleton.

xp: in %% FTTP parser, I saw no real problem. The “user” is LoaderFactory.java. I could be wrong but don’t think it and my singleton are tightly coupled, and complicating unit test.

open-call in FTTP loader singleton

To prevent deadlock, we took care to adopt open-call in our synchronized singleton constructor.

Basically, our long constructor (any long constructor) tend to make calls to other objects. Eventually, one of the calls that another programmer add may invoke a method that invoke a synchronized method. Now step back and count how many locks are involved.

Some may question this is over-cautious — the class doesn’t have any other static synchronized method. But Future?

Open-call is defensive design.

singleton race condition

http://www.javaworld.com/cgi-bin/mailto/x_java.cgi says

// Also an error, synchronization does not prevent
// two calls of constructor.
0) public static MySingleton getInstance() {
1) if (_instance==null) {
2) synchronized (MySingleton.class) {
3) _instance = new MySingleton();
4) }
5) }
6) return _instance;
7) }

Thread A passes Line 1
Thread B passes Line 1
Thread A gets the lock at Line 2 and releases it at Line 4
Thread A passes Line 7, sets _instance to point to a MySingleton object and returns it to caller who creates a reference to the object.
Thread B gets the lock at Line 2 and instantiates a second MySingleton.

Now both instances have reference count > 0

1 singleton 2 instances

Hi guys,

I think we have a few methods like this, which could produce 2 instances of the singleton.

public static FTTPCktLoader getInstance() { 
1) if (_instance != null) { 
2)   return _instance; 
3) } 
4) synchronized (FTTPCktLoader.class) { 
5)   _instance = new FTTPCktLoader(); 
6) } 
7) return _instance; 

Thread A goes through 123 and gives way to other threads
Thread B goes through 123, since _instance is still null
B gets the lock and goes through 4567 and returns a new object to its caller method
B gives way to other threads
A gets the lock and goes through 4567 and returns a second object to its caller method

Now, the caller method (probably in LoaderFactory) may be synchronized, but that would not be a safe design. Another programmer may write another caller method that calls getInstance() without acquring any lock.

I’ll find a new version later, hopefully more thread-safe.