Skip to content

Instantly share code, notes, and snippets.

@justADeni
Last active November 25, 2025 23:10
Show Gist options
  • Select an option

  • Save justADeni/35091357bb139069560f892fa6e4a584 to your computer and use it in GitHub Desktop.

Select an option

Save justADeni/35091357bb139069560f892fa6e4a584 to your computer and use it in GitHub Desktop.
Lazy Supplier
import java.util.function.Supplier;
@FunctionalInterface
interface Lazy<T> extends Supplier<T> {
T get();
static <T> Lazy<T> of(Supplier<T> supplier) {
return new LazyImpl<>(supplier);
}
}
final class LazyImpl<T> implements Lazy<T> {
private final Supplier<T> supplier;
private T value;
LazyImpl(Supplier<T> supplier) {
this.supplier = supplier;
}
@Override
public T get() {
if (value == null) value = supplier.get();
return value;
}
}
@justADeni
Copy link
Author

Note: Not thread-safe. If you want thread safety, you need to synchronize it yourself.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment