Java – can any unused object escape from the garbage collector?

Are there any objects that may not be referenced anywhere and still exist on the heap I mean, an unused object may escape from the garbage collector and be on the heap until the end of the application

Want to know, because if it's there, I can be more cautious in coding

Solution

If an object is no longer referenced, it still exists on the heap, but it can also be garbage collected freely (unless we are talking about class objects, which exist in permgen space and will never be garbage collected - but is this usually something you need to worry about)

There is no guarantee of how long, but your application will not run out of memory until the memory of these objects is reclaimed

However, garbage collection does involve overhead, so if you create more objects than you need and you can easily create fewer objects, be sure to do so

Edit: in response to your comment, if an object is indeed not referenced by anything, it will be recycled during garbage collection (assuming you are using sun's latest JVM; I can't say other implementations) The reason is as follows: all objects are allocated continuously on the heap When GC is about to occur, the JVM follows all references to "tagged" objects it knows can access - and then moves these objects to another clean area Old areas are considered free memory Anything that cannot be found by reference cannot be moved The key is that GC does not need to "find" unreferenced objects If so, I will be more worried about objects that are still referenced when they are not intended, which will lead to memory leakage

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>