Originally published on 2018-04-27
The cost of postponed lazy field init in Java is checking if field is null every time we need to get the value
Note: T implements Singleton pattern.
class Clazz{
//static instance holder
private static Clazz instance;
// private constructor
private Clazz{
// some expensive instantiation
}
// getter
public static Clazz getInstance() {
if(instance == null){
instance == new Instance();
}
return instance;
}
}
Is it possible while utilising Java 8 lambdas to improve performance? Apparently, there is Supplier interface for that!
class Clazz{
private Supplier fooField = () -> {
Clazz val = expensiveInit();
fooField = () -> val;
return val;
};
public Clazz getFoo(){
return fooField.get();
}
}
PS. This is not thread safe.