I have the following class
class Singleton
{
private:
static Singleton *p_inst;
Singleton();
public:
static Singleton * instance()
{
if (!p_inst)
{
p_inst = new Singleton();
}
return p_inst;
}
};
Please do elaborate on precautions taken while implementing Singleton in multi-threaded environment .
Definition of singleton 1 : a card that is the only one of its suit originally dealt to a player. 2a : an individual member or thing distinct from others grouped with it. b : an offspring born singly singletons are more common than twins.
Example. The Singleton pattern ensures that a class has only one instance and provides a global point of access to that instance. It is named after the singleton set, which is defined to be a set containing one element. The office of the President of the United States is a Singleton.
It is used where only a single instance of a class is required to control the action throughout the execution. A singleton class shouldn't have multiple instances in any case and at any cost. Singleton classes are used for logging, driver objects, caching and thread pool, database connections.
Singleton pattern is one of the simplest design patterns in Java. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object.
In multi-threading that clause
if(!p_inst)
{
p_inst = new Singleton();
}
is actually 3 separate actions. You are getting the value of p_inst
, setting the value of p_inst
and writing the value of p_inst
. So get-set-write means that you need to put a lock around p_inst
otherwise you can have 2 threads which create a Singleton
value that each thread uses.
Here is how you can view the issue, assume that your Singleton
has a mutable field val
:
thread A -> p_inst is NULL
thread B -> p_inst is NULL
thread A -> set to Singleton (1)
thread B -> set to Singleton (2)
thread C -> p_inst is Singleton (2)
thread A -> set val to 4
thread B -> set val to 6
thread C -> get val (it's 6)
thread A -> get val (it's 4!!)
You see? There's 2 copies of a Singleton floating about, neither of which knows about the other. The third thread which checks on the Singleton
is only going to see the last assignment. But with locking, you can prevent multiple assignment and these types of problems.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With