Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this Comparer class from SSCLI library code ThreadSafe?

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?

like image 407
drr Avatar asked May 17 '26 00:05

drr


1 Answers

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.

like image 156
Hans Passant Avatar answered May 19 '26 13:05

Hans Passant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!