title: WeakReference of a Collection in java
body: <p><strong>Backstory</strong></p>
  
  <p>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:</p>
  
  <pre><code>List&lt;Bob&gt; list = cache.asList();
  List&lt;Bob&gt; otherList = cache.asList(); // use from cache, if still available
  </code></pre>
  
  <p>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 <code>WeakReference</code> for this, to allow using it if its not collected.</p>
  
  <p><strong>Question</strong></p>
  
  <p>If I have a <code>WeakReference&lt;List&lt;Bob&gt;&gt;</code> 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?</p>
  
  <p>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?</p>
  
  <p><strong>Clarifications</strong></p>
  
  <p>I'm not interested in the reachability of the list, I know that the list is inside the <code>WeakReference</code> 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? </p>