Last active
April 13, 2018 16:50
-
-
Save SimonMarquis/df272a615e10b2265442ce1b6882df70 to your computer and use it in GitHub Desktop.
LazyGetter, from Cyril Mottier https://cyrilmottier.com/2016/06/20/launch-screens-from-a-tap-to-your-app/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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