Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a java 8 method reference be garbage collected if the parent class isn't?

Tags:

java

java-8

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.

like image 918
pranahata Avatar asked Dec 24 '22 23:12

pranahata


1 Answers

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.

like image 186
Holger Avatar answered Dec 28 '22 07:12

Holger