0

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

klobin
  • 41
  • 1
  • 11

5 Answers5

4

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.

Cameron
  • 1,868
  • 3
  • 21
  • 38
1

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.

Jens Schauder
  • 77,657
  • 34
  • 181
  • 348
  • But as I have stated they can be use once blue moon,So thus it not reffered regularly ,and it happens to be collected by GC – klobin Jul 16 '14 at 06:06
  • If there is a reference from a living thread it won't get collected, no matter how long you don't use it. If you don't have a reference ... how do you intend to use it later on? – Jens Schauder Jul 16 '14 at 06:14
0

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

TheLostMind
  • 35,966
  • 12
  • 68
  • 104
  • I respect ur answer but as I have stated it will be used in future scope so tht's why,I need that object .Just I have to make sure it is not GCed,and even my CPU is not used tht much . – klobin Jul 16 '14 at 06:02
  • @klobin - in that case. *klobin's* answer would work. You just need to keep strong references for those objects and ensure that the container that keeps these references isn't GCed. – TheLostMind Jul 16 '14 at 06:05
0

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

DarrenCibis
  • 865
  • 10
  • 25
0

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 G.C. Until The Execution Of Your Code. Just Have A Global Reference To That Object.

prince
  • 2,636
  • 1
  • 11
  • 3