Search code examples
javagarbage-collectionfinalanonymous-class

Java final anonymous class vs garbage collector


My question is about how should we use anonymous class when passed as parameter to async callback ? For example if I have the following code :

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
        });
}

calling "makeJob" in a loop by allocating each time new listener (MyListener) that is used later by the "onResponse", this listener could become eligible for garbage collector ? Is need to keep one reference to this listener to be sure that when used later in "onResponse" is not already garbaged ?


Solution

  • Objects become eligible for garbage collection when no other objects reference them.

    In your case, the MyListener objects are passed down to makeJob, where they are then referenced by the CallbackInterface objects. Note that the reference does not need to be a member variable explicitly declared within CallbackInterface (actually, the java runtime generates one and copies the reference).

    So as long as the CallbackInterface object exists, its associated MyListener will not be garbage collected. This means that as long as doAsyncJob keeps a reference to the CallbackInterface for as long as the job is running, then the MyListener will always be available.