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