简体   繁体   中英

How to avoid object collection by garbage collector

I have some objects in my code which are not invoked in everyloop,But they are useful in future when some forced termination from loop,unpredictable error etc happens, So how to make sure that this objects are not ever collected by garbage collector .

For example : I have one class so I dont want GC to perform any Garbage collection on this class

If the objects are valuable and expensive to create, you should hang on to them in a field in your class. You could create a Map that would act sort of like a cache and grab them out of the Map when you're ready to use them again.

Keep a strong reference to the object, Doing this will always ensure that your object will not be GCed. I would also leave such things to the Garbage collector which I think is smarter than us(with all due respect) when it comes to memory management

You should have a look at the scope of your variables. as long as they are in scope they should not be garbage collected.

If they are useful in the future you have a reference to these objects somewhere. This is enough to ensure that they will never be garbage collected.

Garbage Collector Simply Avoids The Object Which Have Any Reference In The Code Further. So If You Want Any Object To Never Get Collected By GC Until The Execution Of Your Code. Just Have A Global Reference To That Object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM