Lazy Supplier Memoized Value
Wrap an expensive initializer in a memoized Supplier so the value is computed on first get and reused afterwards without re-running the loader.
Code
import java.util.function.Supplier;
public class LazyConfig {
public static void main(String[] args) {
Supplier<String> config = lazy(() -> {
System.out.println("constructing (should print exactly once)");
return "db=prod;pool=8";
});
System.out.println("not yet constructed");
System.out.println("first get: " + config.get());
System.out.println("second get: " + config.get());
}
// 单线程懒加载:第一次 get 才计算,之后复用同一结果
static <T> Supplier<T> lazy(Supplier<? extends T> origin) {
return new Supplier<T>() {
private T value;
private boolean loaded;
@Override
public T get() {
if (!loaded) {
value = origin.get();
loaded = true;
}
return value;
}
};
}
}Inside the snippet
Lazy Supplier Memoized Value comes down to the class LazyConfig and the functions main, lazy and get.
Putting it to use
Running the file prints labeled results such as constructing (should print exactly once), not yet constructed, first get: — each operation’s effect is visible in the output.
Launch the file; main takes over and steps through lazy and get.
Core lines
return new Supplier<T>() {
private T value;
private boolean loaded;
@Override
public T get() {
if (!loaded) {
value = origin.get();
loaded = true;
}
return value;
}
};
return "db=prod;pool=8";
Interactive Tools for This Topic
FAQ
- What does Lazy Supplier Memoized Value print when run?
- The script runs standalone; its 4 labeled outputs include `constructing (should print exactly once)`, `not yet constructed`, `first get:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.