The enclosing instance here isn't eligible for garbage collection as long as the enclosed instance is alive, right?
interface Foo<T> {
T compute();
default Foo<T> memoize() {
return new Foo<>() {
T result = null;
boolean cached = false;
@Override
public T compute() {
if (!cached) {
result = Foo.this.compute();
cached = true;
}
return result;
}
};
}
}
Does this solve that problem?
interface Foo<T> {
T compute();
default Foo<T> memoize() {
return Foo.memoize(this);
}
private static <T> Foo<T> memoize(Foo<T> original) {
class Bar implements Foo<T> {
T result = null;
Foo<T> foo;
Bar(Foo<T> original) {
foo = original;
}
@Override
public T compute() {
if (foo != null) {
result = foo.compute();
foo = null;
}
return result;
}
}
return new Bar(original);
}
}