3

I have a class(A) with constructor defined as shown below. In the constructor, I have created an object for B by passing a listener(interface) implementation to it as shown below.

public class A {

    private String str;

    public A() {

       new B(new OnStringUpdatedListener() {

           public void onStringUpdated(String str) {
               A.this.str = str;
           }

       });
    }
}

In the above code object of B is not assigned to any field of A or a variable in constructor.

What is the lifetime of the object of B? Is it marked for garbage collection as soon as constructor execution completed or is it still alive since it registered a listener which modifies A's field.

Vamshi
  • 133
  • 1
  • 9
  • 4
    That depends on what `B` actually looks like but assuming nothing would prevent it from being elligible for garbage collection chances are high the it will be marked and evicted the next time the garbage collector is running. I said "chances" because there are not guarantees on what the garbage collector will do nor when it will run - for performance or other reasons it _might_ ignore that object (though that is unlikely). – Thomas Mar 14 '19 at 09:56

1 Answers1

4

@Thomas' comment is nice.

It doesn't matter what OnStringUpdatedListener modifies. After constructor has been executed, B won't be accessible through any references. It will become eligible for the GC and may be garbage-collected.

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
  • Thanks for the answer. If i have to extend the lifetime of B as that of A then I should assign object of B to a field of A, right? – Vamshi Mar 14 '19 at 10:14
  • 1
    @Vamshi yes, you need someone long-lived to refer to `B` in order to keep it alive: a field of `A` would be fine. – Andrew Tobilko Mar 14 '19 at 10:20
  • Thanks @Andrew. This is helpful. I got this from an IDE suggestion to convert that the field which holds the reference of `B` to local variable because I am not using it anywhere in class A except constructor. – Vamshi Mar 14 '19 at 10:26