Dear ladies and sirs.
This question is in continuation of this one. The deal is simple.
Given:
- A collection of lazily created singletons.
- Multithreaded environment.
Wanted:
- An implementation with as little lock penalty as possible when an already created object is accessed. It is OK to pay higher penalty on removal or lazy initialization of a new object.
Let us consider the good old C++ style implementation of a singleton, used as an illustration of the if-lock-if pattern:
public static SomeType Instance
{
get
{
if (m_instance == null)
{
lock(m_lock)
{
if (m_instance == null)
{
m_instance = new SomeType();
}
}
}
return m_instance;
}
}
Again, this is just an illustration of the if-lock-if pattern.
Clearly, there is no lock penalty at all when accessing an already constructed object. Is it possible to devise a collection of lazily created objects in the same spirit of keeping the penalty minimal when the particular object is already created? It is fine to pay higher penalty when the object is removed.
Thanks.
EDIT:
I have rewritten the question to completely erase the word singleton from it, since people tend to attribute too much attention to it and not to the core of the question.