private static class ValueHolder{
static final String value = "Lazy initialized";
}
public static String getValue(){
return ValueHolder.value;
}
instance field uses double check
private volatile String value;
public String getValue(){
String result = value;
if (result == null){
synchronized (this){
result = value;
if (result == null){
value = result = "LazyInitialized";
}
}
}
return result;
}
if you don't mind re-creating instance again, You can use single check
public String getValue(){
String result = value;
if (result == null){
value = result = "LazyInitialized";
}
return result;
}
No comments:
Post a Comment