Java 最终匿名 class vs 垃圾收集器
Java final anonymous class vs garbage collector
我的问题是当作为参数传递给异步回调时,我们应该如何使用匿名 class?
例如,如果我有以下代码:
interface MyListener {
void onSucces(String requestedAction, JSONObject response);
void onError(String requestedAction, JSONObject response, int statusCode);
};
interface CallbackInterface {
void onResponse(String requestedAction, JSONObject response, int statusCode);
};
void doAsyncJob(String action, CallbackInterface callbackItf);
void makeJob(String action, final MyListener listener) {
doAsyncJob(action, new CallbackInterface {
void onResponse(String requestedAction, JSONObject response, int statusCode) {
if (statusCode == 200) {
listener.onSucces(requestedAction, response);
} else {
listener.onError(requestedAction, response, statusCose);
}
}
});
}
for(i = 1; i < 1000; i++) {
makeJob("Action_" + i, new MyListener{
void onSucces(String requestedAction, JSONObject response) {
//process response
}
void onError(String requestedAction, JSONObject response, int statusCode) {
//process error
});
}
通过每次分配新的侦听器 (MyListener) 在循环中调用 "makeJob"
"onResponse",此侦听器可能符合垃圾收集器的条件?
是否需要保留一个对此侦听器的引用以确保稍后在 "onResponse" 中使用时不会被垃圾处理?
当没有其他对象引用对象时,对象有资格进行垃圾回收。
在您的例子中,MyListener
对象被传递给 makeJob,然后它们被 CallbackInterface
对象引用。请注意,引用不需要是在 CallbackInterface
中显式声明的成员变量(实际上,java 运行时会生成一个并复制引用)。
因此只要 CallbackInterface
对象存在,其关联的 MyListener
就不会被垃圾回收。这意味着只要 doAsyncJob 在作业 运行 期间保持对 CallbackInterface
的引用,那么 MyListener
将始终可用。
我的问题是当作为参数传递给异步回调时,我们应该如何使用匿名 class? 例如,如果我有以下代码:
interface MyListener {
void onSucces(String requestedAction, JSONObject response);
void onError(String requestedAction, JSONObject response, int statusCode);
};
interface CallbackInterface {
void onResponse(String requestedAction, JSONObject response, int statusCode);
};
void doAsyncJob(String action, CallbackInterface callbackItf);
void makeJob(String action, final MyListener listener) {
doAsyncJob(action, new CallbackInterface {
void onResponse(String requestedAction, JSONObject response, int statusCode) {
if (statusCode == 200) {
listener.onSucces(requestedAction, response);
} else {
listener.onError(requestedAction, response, statusCose);
}
}
});
}
for(i = 1; i < 1000; i++) {
makeJob("Action_" + i, new MyListener{
void onSucces(String requestedAction, JSONObject response) {
//process response
}
void onError(String requestedAction, JSONObject response, int statusCode) {
//process error
});
}
通过每次分配新的侦听器 (MyListener) 在循环中调用 "makeJob" "onResponse",此侦听器可能符合垃圾收集器的条件? 是否需要保留一个对此侦听器的引用以确保稍后在 "onResponse" 中使用时不会被垃圾处理?
当没有其他对象引用对象时,对象有资格进行垃圾回收。
在您的例子中,MyListener
对象被传递给 makeJob,然后它们被 CallbackInterface
对象引用。请注意,引用不需要是在 CallbackInterface
中显式声明的成员变量(实际上,java 运行时会生成一个并复制引用)。
因此只要 CallbackInterface
对象存在,其关联的 MyListener
就不会被垃圾回收。这意味着只要 doAsyncJob 在作业 运行 期间保持对 CallbackInterface
的引用,那么 MyListener
将始终可用。