A reader wrote in some time after we ran a short series on the Singleton pattern with some questions. These included how to construct a singleton when the class has a non-trivial constructor with arguments that are calculated at run-time, and how to use the singleton in a multi-threaded environment. If you were wondering about these issues as well, keep reading.
Some time ago I had a short email exchange with one of the DevHardware readers. He originally sent me an email with a couple of good questions about the Singleton Pattern articles I wrote. After answering his questions he suggested that the things we discussed in email might be worth another article on the Singleton pattern.
I think that he was right. There are some issues I haven’t touched upon that can give you serious problems in certain settings. Articles and books are nice until you face the problem of adapting the information you get from them to your own needs.
The first problem he ran into was how to construct a singleton when the class has a non-trivial constructor with arguments that are calculated at run-time. In the code I provided with my previous articles about the singleton, the class was instantiated in a Creation class which was called a creation policy. They assume that the object that has to be created inside the singleton supports a default constructor (one that takes no arguments).
The next question he had was whether it was safe to use the singleton code I provided in a multi-threaded environment. Well… it is not. So I'm taking his advice and revisiting the Singleton Pattern based on his questions.