Java - is there any reason to check if a singleton is null twice?

前端 未结 5 1968
傲寒
傲寒 2020-12-18 00:42

I have come across some code, where the developer is constantly checking if the singleton is null twice with a nested if - like in the code below:

private st         


        
5条回答
  •  渐次进展
    2020-12-18 01:17

    Your code doesn't demonstrate the case properly. This stems from the double-checked idiom, where it does make sense:

    // Double-check idiom for lazy initialization of instance fields.
    private volatile FieldType field;
    FieldType getField() {
        FieldType result = field;
        if (result == null) { // First check (no locking)
            synchronized(this) {
                result = field;
                if (result == null) // Second check (with locking)
                    field = result = computeFieldValue();
            }
        }
        return result;
    }
    

    Read about it over here.

    Be careful to note that this idiom is a good choice only for instance fields. In your question you have a static field, for which case a much simpler idiom is the primary choice: the lazy initialion holder class idiom:

    // Lazy initialization holder class idiom for static fields
    private static class FieldHolder {
        static final FieldType field = computeFieldValue();
    }
    static FieldType getField() { return FieldHolder.field; }
    

提交回复
热议问题