Garbage collection when final variables used in an

2019-04-23 17:44发布

问题:

If I have code similar to the following:

public Constructor(final Object o) {
    taskSystem.add(new CycleTask(15, 15, -1) {

        @Override
        public void execute() throws Throwable {
            //access o here every 15 cycles forever
        }
    });
}

When would o be garbage collected, if ever? Only when the task has been collected, or will it remain in memory forever because it's final?

回答1:

o might get garbage collected once it is not reachable any longer, whether it is final or not. Obviously, as long as execute is running, if it needs to access o, it will prevent GC.

When execute is done running, and assuming you have not stored any references to o (for example in a collection), it will be flagged as ready for garbage collection.



回答2:

When the anonymous class instance becomes eligible for garbage collection, if nothing else refers to the object that o referred to when the method was called, that object will become eligible for garbage collection.

There's nothing special about final variables which deters garbage collection.



回答3:

'final' has no effect on GC. The object will become eligible for collection when it becomes unreachable. In this case there are at least three references, any one of which can stop that: the 'final' parameter, which disappears when the method returns; the caller's reference; and the copy of the final variable in the anonymous class instance.



回答4:

There is no relationship between final keyword and the lifetime of the variable.

It will be garbage collected when not needed anymore, and since it's a parameter this can happen just outside the method (if there is no reference outside).

The final keyword is just a constraint given to the compiler to forbid any further modification of the reference o after the call of the function.