Leg*_*ege 6 java lambda garbage-collection weak-references java-8
我创建了一个名为Foo. 当我创建一个名为 的 lambda 或方法引用时Action,该Action对象持有对Foo.
我将动作传递给另一个班级。但是如果我把它当作一个弱引用,它会立即得到 gc,因为没有人存储对Action.
但是如果我把它当作一个强引用,它就Foo不能是 gc,因为它有一个引用Action。
所以内存泄漏发生,我想防止它。
我的问题是:如何在Action不阻止Foo.
例子:
Interface Action {
void invoke();
}
Class Foo() {
public void someMethod() {
....
}
}
Class Holder() {
WeakRefrence<Object> foo;
public Action action;
void register(Object source, Action a) {
foo = new WeakReference(source);
??? how can i hold the action without prevent source to gc able.
}
}
main() {
Holder holder = new Holder();
Foo foo = new Foo();
Action action = foo::someMethod;
holder.register(foo,action);
action = null;
System.gc();
//only the holder store reference to action.
//if i store in holder as weak reference i cannot invoke it any more cause it get gc.
//foo = null;
//System.gc();
//if i grab action in holder as strong refrence the foo cant be gc cause action hold refernce to it.
holder.action.invoke();
}
Run Code Online (Sandbox Code Playgroud)