Skip to content

Instantly share code, notes, and snippets.

@ezksd
Created February 15, 2017 06:45
Show Gist options
  • Save ezksd/96d4b748daa3942b92d53aeca94c9216 to your computer and use it in GitHub Desktop.
Save ezksd/96d4b748daa3942b92d53aeca94c9216 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> outerSup;
LazyThreadSafe(Supplier<T> sup) {
this.outerSup = new UnEvaled(sup);
}
class UnEvaled implements Supplier<T>{
Supplier<T> innerSup;
UnEvaled(Supplier<T> sup) {
innerSup = sup;
}
public synchronized T get() {
if (innerSup == null) {
return outerSup.get();
} else {
T val = this.innerSup.get();
innerSup = null;
outerSup = () -> val;
return val;
}
}
}
@Override
public T get() {
return outerSup.get();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment