How to prevent GC to collect weakly referenced object?
I have开发者_StackOverflow社区 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);
Is obj a strong or a weak ref?
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.
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.
As soon as you line Object obj = Cache.getObject(key)
is executed, object referenced by obj
is now strongly referenced and will not be garbage collected (but when obj
is out of scope the referenced object may became eligible for garbage collection).
If you don't want something to get GC'ed, you should hold a strong reference to it. If the performance of a piece of code would be adversely affected by having objects disappear the microsecond the last strong reference was invalidated, that code should be considered broken.
The primary place weak references are essential is in situations where an object has a reference to something that it doesn't really care about, but which it is expected to update or watch in case there are other objects that do care about it. For example, a socket monitor might take all incoming packets and put them into a queue so that a packet-log window could pull them out and display them. If the object that's supposed to read from the queue were to disappear without notifying the socket monitor, and the socket monitor had a strong reference to the queue, it could keep adding packets to the queue even though nobody would ever be interested in reading them. If, however, the socket monitor used a WeakReference for the queue, then at some point after the object that was supposed to read from the queue disappeared the queue would become eligible for garbagecollection (since the socket monitor would only hold a weak reference). Once the queue was garbage-collected, the socket monitor could notice that its WeakReference had been invalidated and could shut itself down.
精彩评论