Possible duplicate:
Is C # static constructor thread safe?
John Skeet's good article at http://csharpindepth.com/Articles/General/Singleton.aspx and the other articles I read make it clear that this double-check lock does not work in both C # and Java if only explicitly does not put the instance as "volatile". If you do not, checking a comparison with a null value may return false, even if the instance constructor has not finished working. In Mr. Skeetβs third example, he clearly states: βThe Java memory model does not guarantee that the constructor will exit before the reference to the new object is assigned to the instance. The Java memory model has been reworked for version 1.5, but the double-even lock still interrupted after that without the volatile variable (as in C #) "
However, most agree (including Mr. Skeet, in examples 4 and 5 in his article), that using static initialization is an easy way to get a streaming single-user instance. He claims that "static constructors in C # are set to execute only when instantiating a class or mentioning a static member and to execute only once for AppDomain."
This makes sense, but what seems to be missing is a guarantee that a link to a new object will only be assigned after the constructor completes - otherwise we will get the same problem that makes a double-check lock if you do not check the instance how volatile. Is there a guarantee that when using static initialization to call the instance constructor (as opposed to calling the instance constructor from the get {} property, as well as when locking with double check), the constructor will be completely filled before any other thread can get a reference to the object?
Thanks!
multithreading constructor c # singleton
Nick w
source share