Garbage collection when final variables used in anonymous classes

烈酒焚心 提交于 2019-12-05 03:14:15

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.

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.

'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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!