The sample code is as follows
public class Lazy<T> implements Supplier<T> {
public Lazy(Supplier<T> supplier) {
this.supplier = Objects.requireNonNull(supplier);
}
Supplier<T> supplier;
T value;
@Override
public T get() {
if (supplier != null) {
synchronized (this) {
if (supplier != null) {
value = supplier.get();
supplier = null;
}
}
}
return value;
}
}
I am worried that if "supplier" is a constructor. "supplier=null" may be executed before the object is initialized. An error similar to "double checked locking broken" may happen.
"supplier.get()==null" may be true in this class. So I don't check if the value is null
If it is thread unsafe, Should I add "volatile" before the "supplier" field? If it is thread safe, why?