Skip to content

Instantly share code, notes, and snippets.

@ezksd
Last active February 17, 2017 01:46
Show Gist options
  • Save ezksd/2f985e6bf290af20110b89188a29b1c2 to your computer and use it in GitHub Desktop.
Save ezksd/2f985e6bf290af20110b89188a29b1c2 to your computer and use it in GitHub Desktop.
import java.util.function.Supplier;
public interface Lazy<T> extends Supplier<T> {
static <T> Lazy<T> of(Supplier<T> sup) {
return new LazyImpl<T>(sup);
}
static <T> Lazy<T> ofSafe(Supplier<T> sup) {
return new LazyThreadSafe<T>(sup);
}
class LazyImpl<T> implements Lazy<T> {
private Supplier<T> sup;
LazyImpl(Supplier<T> sup) {
this.sup = () -> {
T val = sup.get();
this.sup = () -> val;
return val;
};
}
@Override
public T get() {
return sup.get();
}
}
class LazyThreadSafe<T> implements Lazy<T> {
private Supplier<T> sup;
LazyThreadSafe(Supplier<T> sup) {
this.sup = new UnEvaled(sup);
}
class UnEvaled implements Supplier<T>{
Supplier<T> init;
UnEvaled(Supplier<T> sup) {
init = sup;
}
public synchronized T get() {
if (sup instanceof LazyThreadSafe.UnEvaled) {
T val = init.get();
sup = () -> val;
return val;
} else {
return sup.get();
}
}
}
@Override
public T get() {
return sup.get();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment