I have a memory-heavy object (foo) and a smaller object (bar) held within. I want to make sure foo is garbage collected but need access to the hello field within my lambda for the lifetime of the program.
I am wondering if there is any logic to first dereferencing bar into its own variable before creating my lambda. I believe that this may allow foo to be garbage collected but am not certain.
I.e. in the following example, as I am only using bar.hello, is there any logic in doing B over A to allow foo to be garbage collected? Does the first lambda (A) implicitly hold a reference to foo, and does the second (B) remove this reference?
class Bar { // Use within lambda
String hello;
}
class Foo { // Memory-heavy class
Bar bar;
String world;
}
Foo foo = new Foo();
// A (access bar through foo, will foo remain in memory?)
run(() -> System.out.println(foo.bar.hello));
// B (foo should have no more references, should be GC'd?)
Bar bar = foo.bar;
run(() -> System.out.println(bar.hello));