Answer the question
In order to leave comments, you need to log in
Is it expensive to use lock, why do Singleton with double check locking?
A person with a very large experience (about 20 years) of programming (senior) once explained to me that lock is a rather expensive operation, because under the hood, lock = try + Monitor.Enter() + finally + Monitor.Release() and it's "very expansive" and so we do like this:
if (_ht == null)
{
lock (_sync)
{
Create();
}
}
public sealed class Singleton1
{
private static volatile Singleton1 _instance;
//locker
private static readonly object Loker = new();
public static Singleton1 Instance
{
get
{
//first check
if (_instance == null)
{
// another Thread may create instance
lock (Loker) // very expensive, because - lock = try + Monitor.Enter() + finally + Monitor.Release()
{
//second check
if (_instance == null)
{
_instance = new Singleton1();
}
}
}
return _instance;
}
}
}
public sealed class Singleton1
{
private static volatile Singleton1 _instance;
//locker
private static readonly object Loker = new();
public static Singleton1 Instance
{
get
{
lock (Loker)
{
// only one check and everything is fine :)
if (_instance == null)
{
_instance = new Singleton1();
}
}
return _instance;
}
}
}
Answer the question
In order to leave comments, you need to log in
why do Singleton with double check locking
they said that lock is one of the cheapest synchronization operations.
get { lock (Loker) { // only one check and everything is fine :) if (_instance == null) { _instance = new Singleton1(); } } return _instance; }
lock is a super cheap operation. Mutex opening/closing - 25 ns. I'm afraid that checking for null-pointer is more expensive, but it's an interesting question. If you figure out this question, which is faster - it will be cool to know.
But in the context of your question, the lock overhead is absolutely ridiculous, since the overhead would be 50 - 100 ns. This is comparable to accessing RAM.
By the way, I often came across in social services that people think that the mutex is implemented somehow programmatically at the OS level or that some kind of magic happens in the virtual machine. But no, it's implemented right at the hardware level, which is why it's so fast.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question