public abstract class Comparer<T> : IComparer, IComparer<T>
{
static Comparer<T> defaultComparer;
public static Comparer<T> Default {
get {
Comparer<T> comparer = defaultComparer;
if (comparer == null) {
comparer = CreateComparer();
defaultComparer = comparer;
}
return comparer;
}
}
First, is the Default property thread safe? Isn't it possible that effect of the following statement
comparer = CreateComparer();
might not be visible to threads other than creating thread? So, multiple instances of Comparer are constructed?
Is Microsoft doing this for the sake of trading synchronization cost off with the cost of creating multiple objects?
Second why defaultComparer is first assigned to comparer variable first...and then later on swapped? why do Comparer comparer = defaultComparer?
Yes. Multiple comparers do indeed get created, defaultComparer gets assigned multiple times. Not a problem, they are all the same. The garbage collector takes care of the extras. And the atomic assignment guarantee that the CLR offers for object references ensures that the static cannot be read incorrectly.