开发者

How to verify/force classes to be garbage collected

I'm in a scenario where I launch applications in a specific Classloader by a entry point defined API, something like "OSGi". And I have made specific methods such as: start and stop. And the applications launched are in an array called applications.

If I want to end the application I would call the stop method of it. However suppose the application is a malicious and it doesn't clean it's class/resources, how can I force it to be garbage collected???

If I do a simple applications开发者_开发百科[i] = null; on the main application, will it force that malicious application who didn't clean any resource to be garbage collected???


If the only reference to the applications is held in applications[i], then this will be needed. However the next GC cycle can't be predicted. So the application may have a longer lifetime than expected


No, you can't tell the garbage collector to force collect a specific object. Setting a reference to null doesn't guarantee anything.

You could run your potentially malicious application in a separate process and terminate the process when you have finished with it. Then the operating system will ensure that all resources (memory and other resources) are freed.


The garbage collector will collect unused objects (objects without reference, that is) on its own. It can't be forced, it can't be predicted well. It can however be asked to run by invoking

System.gc()

Note that this does not garantee anything either, it merely "suggests" that the garbage collection should begin. But this is genereally considered bad practice because it can seriously impact the performance of the garbage collection process and the JVM.

So in most cases it is best to insure that there are no references left so the object can be collected when the GC deems it appropriate.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜