I'm a bit confused with java 8's 'closure'. It supposedly closes over values. Consider the following class.
public class SomeClassWithLargeMemoryFootprint {
//some state
private SomeObject someObj;
//some more state
public void doSomething(SomeAsyncHelper helper) {
helper.doAsync( () -> {
//some super slow operation
int foo = someObj.whatever();
//some more stuff
});
}
}
.
//Let's assume SomeAsyncHelper.doAsync takes a VoidRunner that looks like below
interface VoidRunner {
void apply();
}
Question is, can an instance of SomeClassWithLargeMemoryFootprint be GC'd when the async helper is still working? It's clear to me that "someObj" can't be GC'd as it is required by the lambda in doSomething(). What about the rest of the state?
Also, consider the following variant where we invoke a member method of the containing class:
public class SomeClassWithLargeMemoryFootprint {
//some state
private SomeObject someObj;
//some more state
public void doSomething(SomeAsyncHelper helper) {
helper.doAsync( () -> {
//do something
memberMethod();
//do something else
});
}
private void memberMethod() {
//do something
}
}
what now? How does the 'helper' know how to execute "memberMethod"? Does it get a reference to the instance of SomeClassWithLargeMemoryFootprint? What would be the GC sequence?