We're running into performance issues, and one potential culprit is a centralized use of a volatile singleton. The specific code is of the form:
class foo {
static volatile instance;
static object l = new object();
public static foo Instance {
if (instance == null)
lock(l) {
if (instance == null)
instance = new foo();
}
return instance;
}
}
This is running on an 8-way box, and we're seeing context switching to the tune of 500,000 per second. Typical system resources are fine - 25% cpu util, 25% memory util, low IO, no paging, etc.
Does using a volatile
field induce a memory barrier or any kind of cpu cache reload? Or does it just go after main memory every time, for that field only?
lock
does induce a memory barrier, so if you are always accessing instance in a lock you don't need the volatile.
According to this site:
The C# volatile keyword implements acquire and release semantics, which implies a read memory barrier on read and a write memory barrier on write.