匿名 Runnable 的这种特殊使用会导致内存泄漏吗?
Will this particular use of an anonymous Runnable cause a memory leak?
private class ProductFragment extends Fragment implements OnGetProductFromDBListener {
Activity a;
void onCreate {
a = getActivity();
new GetProductFromDB();
}
void onGetProductSuccess(Product product) { // This is not called from the main thread because of the implementation of GetProductFromDB
a.runOnUiThread(new Runnable() {
void run() {
// do some UI and Views related stuff
}
});
}
}
现在,作为匿名的 Runnable class 应该持有对 Fragment 的显式引用,对吧?这将防止片段被垃圾收集?
我应该担心内存泄漏的发生吗?我应该如何预防它?
如果我实例化一个 class 扩展 Runnable 并将其设为静态会有帮助吗?
private static class RunnableTask extends Runnable {
ProductFragment fragment;
public RunnableTask (ProductFragment fragment) {
this.fragment = fragment;
}
void run() {
if(fragment.someBoolean) {
fragment.doSomething();
}
}
}
RunnableTask runnable = new RunnableTask();
a.runOnUiThread(runnable)
严格来说,不一定会导致内存泄漏。但是 - 在线程的 运行 期间,它将持有对外部 class 的引用(在您的情况下为 ProductFragment )。因此,是否是内存泄漏将取决于线程将 运行 持续多长时间,以及它最终是否成为 ProductFragment class.
的唯一引用。
您建议将其分解为静态内部 class 是一个很好的建议,因为这将删除对外部 class 的引用,从而消除潜在内存泄漏的任何可能性。
但是 - 在您的情况下,鉴于您建议的静态 class 仍然保留对外部 class 实例的引用,这样做没有任何好处。
private class ProductFragment extends Fragment implements OnGetProductFromDBListener {
Activity a;
void onCreate {
a = getActivity();
new GetProductFromDB();
}
void onGetProductSuccess(Product product) { // This is not called from the main thread because of the implementation of GetProductFromDB
a.runOnUiThread(new Runnable() {
void run() {
// do some UI and Views related stuff
}
});
}
}
现在,作为匿名的 Runnable class 应该持有对 Fragment 的显式引用,对吧?这将防止片段被垃圾收集?
我应该担心内存泄漏的发生吗?我应该如何预防它?
如果我实例化一个 class 扩展 Runnable 并将其设为静态会有帮助吗?
private static class RunnableTask extends Runnable {
ProductFragment fragment;
public RunnableTask (ProductFragment fragment) {
this.fragment = fragment;
}
void run() {
if(fragment.someBoolean) {
fragment.doSomething();
}
}
}
RunnableTask runnable = new RunnableTask();
a.runOnUiThread(runnable)
严格来说,不一定会导致内存泄漏。但是 - 在线程的 运行 期间,它将持有对外部 class 的引用(在您的情况下为 ProductFragment )。因此,是否是内存泄漏将取决于线程将 运行 持续多长时间,以及它最终是否成为 ProductFragment class.
的唯一引用。您建议将其分解为静态内部 class 是一个很好的建议,因为这将删除对外部 class 的引用,从而消除潜在内存泄漏的任何可能性。
但是 - 在您的情况下,鉴于您建议的静态 class 仍然保留对外部 class 实例的引用,这样做没有任何好处。