Name for this pattern? (Answer: lazy initialization with double-checked locking)

前端 未结 4 1079
谎友^
谎友^ 2021-01-23 02:45

Consider the following code:

public class Foo
{
    private static object _lock = new object();

    public void NameDoesNotMatter()
    {
        if( SomeDataDo         


        
4条回答
  •  佛祖请我去吃肉
    2021-01-23 03:13

    Though I can see how you might think this looks like double-checked locking, what it actually looks like is dangerously broken and incorrect double-checked locking. Without an actual implementation of SomeDataDoesNotExist and CreateSomeData to critique we have no guarantee whatsoever that this thing is actually threadsafe on every processor.

    For an example of an analysis of how double-checked locking can go wrong, check out this broken and incorrect version of double-checked locking:

    C# manual lock/unlock

    My advice: don't use any low-lock technique without a compelling reason and a code review from an expert on the memory model; you'll probably get it wrong. Most people do.

    In particular, don't use double-checked locking unless you can describe exactly what memory access reorderings the processors can do on your behalf and provide a convincing argument that your solution is correct given any possible memory access reordering. The moment you step away even slightly from a known-to-be-correct implementation, you need to start the analysis over from scratch. You can't assume that just because one implementation of double-checked locking is correct, that they all are; almost none of them are correct.

提交回复
热议问题