Interview question: Objects eligible for garbage collection

前端 未结 7 878
无人共我
无人共我 2020-12-02 19:03

Give the following code:

class A {
    Boolean b;
    A easyMethod(A a){
        a = null;
        return a;
    }
    public static void main(String [] args         


        
7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-02 19:42

    First of all the interviewer is wrong about the Boolean -- there is no such object created by this code so there's nothing to be garbage collected.

    It is incorrect to speak of variables like b and a2 as being garbage collected. Objects are garbage-collected, not variables. If an in-scope variable references an object, then it cannot be garbage-collected. Simplistically, it's only when an an object is no longer referenced by any variable that it can be garbage collected.

    So we have three instances of A being created in this code. They start out referenced by a1 etc. but since variable references change I'll refer to the object instances as A1, A2, and A3. Since you haven't shown a definition of the go method I'm going to assume it's meant to be a call to easyMethod.

    Since the variable a1 is reassigned to null, nothing is pointing to instance A1, so it can be garbage-collected.

    Since the variable a2 is never reassigned (the assignment in easyMethod does not affect the original variable), instance A2 cannot be garbage-collected.

    Since easyMethod always returns null and a3 is assigned the result of that method, nothing is pointing to instance A3, so it can also be garbage-collected.

提交回复
热议问题