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

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

  •  13-04-2022
  •  | 
  •  

Question

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!!!

Was it helpful?

Solution

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

OTHER TIPS

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)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top