10

I know that with a WeakReference, if I make a WeakReference to something that unless there's a direct reference to it that it will be Garbage Collected with the next GC cycle. My question becomes, what if I make an ArrayList of WeakReferences?

For example:

ArrayList<WeakReference<String>> exArrayList;
exArrayList = new ArrayList<WeakReference<String>>();
exArrayList.add(new WeakReference<String>("Hello"));

I can now access the data with exArrayList.get(0).get().

My question becomes: This is WeakReference data, will the data located at exArrayList.get(0) be GC'd with the next GC cycle? (even IF I don't make another direct reference to it) or will this particular reference stick around until the arraylist is emptied? (eg: exArrayList.clear();).

If this is a duplicate I haven't found it with my keywords in google.

Florent Bayle
  • 11,520
  • 4
  • 34
  • 47
codingNewb
  • 470
  • 1
  • 8
  • 23

3 Answers3

28
  1. exArrayList.add(new WeakReference<String>("Hello")); is a bad example because String literals are never GC-ed

  2. if it were e.g. exArrayList.add(new WeakReference<Object>(new Object())); then after a GC the object would be GC-ed, but exArrayList.get(0) would still return WeakReference, though exArrayList.get(0).get() would return null

dsh
  • 12,037
  • 3
  • 33
  • 51
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
7

The data at exArrayList.get(0) is the WeakReference. It is not by itself a weak reference, so it will not be collected...

BUT the object referenced by exArrayList.get(0) is weakly referenced, so it might be GCed at any time (of course, that requires that there are no strong references to that object).

So

data.get(0) won't become null, but data.get(0).get() might become.

In other words, the list does not references the weak referenced object but the weak reference itself.

Florent Bayle
  • 11,520
  • 4
  • 34
  • 47
SJuan76
  • 24,532
  • 6
  • 47
  • 87
3

This is a bad idea as the other posters explained above (reference objects not freed). Use a WeakHashMap with the objects as keys and some dummy values ("" or Boolean.TRUE or similar).

Stefan Reich
  • 1,000
  • 9
  • 12
  • I see a lesser concern in "reference objects not freed" than the tremendous overhead of a HashMap where you don't really need it. – xeruf Nov 06 '17 at 00:13
  • 1
    I do sometimes use List> for lack of a LinkedWeakHashMap. Just make sure to clean the list sometimes. – Stefan Reich Jul 18 '18 at 18:32
  • HashMap doesn't have that much overhead. The point here is that its overhead is a fixed factor, whereas the List approach can grow indefinitely, even if no objects are actually in it anymore. – Stefan Reich Oct 19 '18 at 14:12