1

I have a class

public final class GGGGG {

    private final String str;

    public GGGGG(final String str) {
        this.str = str;
    }

    public void showElement(final String test){
        System.out.println(this.str+test);
    }

    public static void main(String[] args) {
        GGGGG hello = new GGGGG("hello");
        final Test2 test2 = new Test2(hello::showElement);
        test2.test();
        hello = null;
        test2.test();

    }

    static class Test2{
        private final Consumer<String> consumer;

        Test2(final Consumer<String> consumer) {
            this.consumer = consumer;
        }

        public void test(){
            this.consumer.accept(" world");
        }
    }
}

What I don't understand, in class GGGG I have String str(state)

I create a consumer with method reference to the method showElement And now this consumer has reference to the GGGGG instance. Does consumer keep a reference to the original object or create a new instance, if it the same reference when it will be garbage collected?

Almas Abdrazak
  • 3,209
  • 5
  • 36
  • 80

1 Answers1

2

Java works with pass-by-value. So, test2 and hello are just a reference copy. You still preserve the information where to reference.

Does consumer keep a reference to the original object?

Yes.

As additional knowledge, the JLS, Section 15.13.3 describes the runtime evaluation of method references.

The timing of method reference expression evaluation is more complex than that of lambda expressions (§15.27.4). When a method reference expression has an expression (rather than a type) preceding the :: separator, that subexpression is evaluated immediately. The result of evaluation is stored until the method of the corresponding functional interface type is invoked; at that point, the result is used as the target reference for the invocation. This means the expression preceding the :: separator is evaluated only when the program encounters the method reference expression, and is not re-evaluated on subsequent invocations on the functional interface type.