Created
February 15, 2017 06:45
-
-
Save ezksd/96d4b748daa3942b92d53aeca94c9216 to your computer and use it in GitHub Desktop.
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.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