I donโt quite understand why there are a bunch of implementation patterns for double checking the lock (apparently, for working with compiler features in different languages). The Wikipedia article on this subject shows a naive method and possible ways to solve the problem, but none of them are so simple (in C #):
public class Foo { static Foo _singleton = null; static object _singletonLock = new object(); public static Foo Singleton { get { if ( _singleton == null ) lock ( _singletonLock ) if ( _singleton == null ) { Foo foo = new Foo();
In Java, you should use synchronized () instead of lock (), but this is basically the same idea. If there is a possible inconsistency when assigning a singleton field, then why not just use the local scope first and then assign the singleton field at the last moment before leaving the critical section? Did I miss something?
Here's the argument of @ michael-borgwardt that in C # and Java a static field is only initialized on first use, but that the behavior is language dependent. And I often used this template to lazily initialize a collection property (e.g. user.Sessions).
Erhhung Jun 13 2018-12-12T00: 00Z
source share