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 foo();
}
}
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?
Generally speaking, on most modern processors a volatile load is comparable to a normal load. A volatile store is about 1/3 the time of a montior-enter/monitor-exit. This is seen on systems that are cache coherent. To answer the OP's question, volatile writes are expensive while the reads usually are not.
The volatile keyword is intended to prevent the compiler from applying any optimizations on objects that can change in ways that cannot be determined by the compiler. Objects declared as volatile are omitted from optimization because their values can be changed by code outside the scope of current code at any time.
For Java, “volatile” tells the compiler that the value of a variable must never be cached as its value may change outside of the scope of the program itself.
The volatile keyword indicates that a field might be modified by multiple threads that are executing at the same time. The compiler, the runtime system, and even hardware may rearrange reads and writes to memory locations for performance reasons.
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.
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