How to create singleton from double check idiom for lazy initialization of instance field? [duplicate]

StackOverflow https://stackoverflow.com/questions/16265746

  •  13-04-2022
  •  | 
  •  

سؤال

private volatile FieldType field;
FieldType getField() {
    FieldType result = field;
    if (result == null) { 
        synchronized(this) {
            result = field;
            if (result == null) 
                field = result = computeFieldValue();
        }
    }
    return result;
}

As we almost all know about this is the sample code for double check idiom for lazy initialization of instance field. But i have a silly doubt here how somebody will create the singleton object of FieldType. As to call the function getField() (which create the singleton instance) you need an instance of the class but till now you don't have the instance. I am bit confused, please let me know. Thanks!!!

هل كانت مفيدة؟

المحلول

Of source the simplest singleton is an enum

enum Singleton {
    INSTANCE;
}

But in this more complicated case,

how somebody will create the singleton object of FieldType.

They have to call getField() which must be static, as does the field

نصائح أخرى

As a first RULE of Singleton

FieldType getField()

should be defined as

public static FieldType getField()

so that method getField() (static method) of FiledType can be invoked, without creating instance

Of course, you need to define private constructor for FieldType (which was missing here)

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top