Skip to content

Instantly share code, notes, and snippets.

@SimonMarquis
Last active April 13, 2018 16:50
Show Gist options
  • Save SimonMarquis/df272a615e10b2265442ce1b6882df70 to your computer and use it in GitHub Desktop.
Save SimonMarquis/df272a615e10b2265442ce1b6882df70 to your computer and use it in GitHub Desktop.
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;
public abstract class LazyGetter<T> {
private final AtomicReference<Optional<T>> mCachedValue = new AtomicReference<>(Optional.<T>empty());
public final T get() {
Optional<T> value = mCachedValue.get();
if (!value.isPresent()) {
synchronized (mCachedValue) {
value = mCachedValue.get();
if (!value.isPresent()) {
mCachedValue.set(Optional.ofNullable(initialValue()));
}
}
}
return mCachedValue.get().get();
}
protected abstract T initialValue();
/**
* Example
*/
private static final LazyGetter<String> LAZY_STRING = new LazyGetter<String>() {
@Override
protected String initialValue() {
return "LazyString";
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment