I have a Singleton class, but it returns two. Do I need two local objects?
public class Manager {
private static Manager _one;
private static Manager _two;
private static object Obj_Lock_one = new object();
private static object Obj_Lock_two = new object();//Do I need Obj_Lock_two here ?
public static Manager GetOne ()
{
if (_one == null)
{
lock (Obj_Lock_one)
{
if (_one == null)
{
_one = new Manager();
}
}
}
return _one;
}
public static Manager GetTwo ()
{
if (_two == null)
{
lock (Obj_Lock_two) //Do I need Obj_Lock_two here ?
{
if (_two == null)
{
_two = new Manager();
}
}
}
return _two;
}
}
Do I need a second lock object? The GetTwo method should use "lock (Obj_Lock_one)" or "lock (Obj_Lock_two)"
If I only use one obj to block, I can just block one thred, I guess ...
What's the correct way?
source to share
Do I need a second lock object?
Using a second lock object here will slightly improve performance if two threads call at the same time GetOne()
and GetTwo()
for the first time at the same time. In other words: you probably won't be able to measure the difference.
What's the correct way?
Don't reinvent the wheel. Revert your code and use instead, instead of "t22> ), which is thread safe and automatically takes care of all these thread synchronization issues:
public sealed class Manager
{
private static readonly Lazy<Manager> lazyOne = new Lazy<Manager>(() => new Manager());
private static readonly Lazy<Manager> lazyTwo = new Lazy<Manager>(() => new Manager());
public static Manager GetOne() { return lazyOne.Value; }
public static Manager GetTwo() { return lazyTwo.Value; }
}
source to share