If I have
public interface Foo {
public void oneMethod();
}
And then I have another class:
public class TestClass {
SoftReference sr;
public test() {
doSomething(this::lalala);
}
public lalala() {
}
public doSomethingFoo(Foo foo) {
sr = new SoftReference(foo);
//can sr.get() ever return null?
}
}
Can sr.get()
ever return null?
Also interested to know the behaviour in the case where instead of a method reference we use an anonymous inner class or a non static inner class.
The life time of an instance created for a method reference does not depend on the target of the method reference. It’s always the other way way round, if your method reference targets a particular instance, the target instance can’t get garbage collected as long as the method reference instance is reachable.
Since the Java specification leaves it open how instances for lambda expressions and method references are created and reused, it’s also unspecified, how long they will live (see A:Does a lambda expression create an object on the heap every time it's executed?).
In practice, with the current implementation, instances which do not capture any values, are remembered and reused and therefore live as long as the class which created them. In contrast, instances which capture values, and this::lalala
captures the value of the this
reference, are not reused and will get garbage collected as soon as they become unreachable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With