Search code examples
javagarbage-collectionweak-references

WeakReference of a Collection in java


Backstory

In a library that I maintain we have an internal map keeping track of our cache. Users of the library are interested in having list access to this map, however we can only provide this by copying its contents (thread-safety reasons). The idea is to cache this list when it is first accessed without having much memory overhead on a second access. To illustrate:

List<Bob> list = cache.asList();
List<Bob> otherList = cache.asList(); // use from cache, if still available

The problem is, we don't want to keep this list forever if its not needed anymore. Since java uses GC we thought it would be appropriate to use a WeakReference for this, to allow using it if its not collected.

Question

If I have a WeakReference<List<Bob>> stored inside my class, what happens if one of the elements becomes weakly reachable (which implies the list is weakly reachable)? Is it possible that the GC decides to just collect the element inside the list or would it look for all other weakly reachable objects referencing it and also collect them, in this case the list?

The problem would be, if the GC collected an element of the list and we then try to access the list again (if thats even possible) what would happen?

Clarifications

I'm not interested in the reachability of the list, I know that the list is inside the WeakReference and that the elements are irrelevant to its reachability. I care about a specific state, in which both the list and an element of the list are weakly reachable and whether it is possible that the GC only collects the element but not the list itself. What exactly does the GC do in this specific scenario?


Solution

  • As long as the List itself is not weakly reachable its elements will not be either. (Assuming the list implementation itself does not use weak references or similar)

    So there is no problem with having the list cached with a weak reference because it would either be garbage collected completely or not at all.