Skip to content

Instantly share code, notes, and snippets.

@bdelacretaz
Last active June 21, 2021 09:57
Show Gist options
  • Save bdelacretaz/d0b12a4eec4c134fdbea06aba66de907 to your computer and use it in GitHub Desktop.
Save bdelacretaz/d0b12a4eec4c134fdbea06aba66de907 to your computer and use it in GitHub Desktop.
///usr/bin/env jbang "$0" "$@" ; exit $?
import java.util.function.Supplier;
public class LazyLoading {
static int callCount = 0;
/** This is the core lazy loading functionality */
static class LazyLoader<T> {
private final Supplier<T> sup;
private T value;
LazyLoader(Supplier<T> sup) {
this.sup = sup;
}
T get() {
if(value == null) {
synchronized(this) {
if(value == null) {
value = sup.get();
}
}
}
return value;
}
}
/** Example using LazyLoader */
static class LazyLoadingPojo {
LazyLoader<Integer> count = new LazyLoader<>(this::computeCount);
public int getCount() {
return count.get();
}
private int computeCount() {
return ++callCount;
}
}
// THE REST IS TESTS //
static void checkThat(String info, boolean value) {
if(!value) {
throw new RuntimeException("Assertion failed: " + info);
}
}
public static void main(String [] args) {
checkThat("Expecting initial callCount to be zero", callCount == 0);
final LazyLoadingPojo p = new LazyLoadingPojo();
checkThat("Expecting callCount still be zero", callCount == 0);
assert(callCount == 0);
for(int i=1; i <= 10; i++) {
p.getCount();
checkThat("At step " + i + ", expecting callCount to remain at 1", callCount == 1);
}
System.out.println("All tests passed, callCount=" + callCount);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment