Search code examples
javareferenceweak-references

How to prevent GC to collect weakly referenced object?


I have an object cache that internally uses weak references and sometimes my object get GCed even if I still need it (so it need to be reload again). My idea is to prevent a GC by adding another reference to that object:

Object obj = Cache.getObject(key);
  1. Is obj a strong or a weak ref?

  2. This seems to work in my case, but I'm not sure if that is the right way so I would appreciate any suggestion.

p.s. I can't change the Cache implementation.


Solution

  • obj is a normal (i.e. a strong) reference.

    The object will not be eligible for GC as long as the variable obj is reachable. So: yes, this will prevent the object from being collected.