Java - WeakReferences with ArrayList?

I know that with WeakReference , if I make WeakReference so that if there is no direct link to it, that it will be garbage collected with the next GC loop. My question becomes, what if I make an ArrayList from WeakReference s?

For example:

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

Now I can access the data using exArrayList.get(0).get() .

My question will be: This is WeakReference data, will the data located in exArrayList.get(0) be GC'd with the next GC loop? (even if I don’t make another direct link to it), or will this particular link stick until the ArrayList is empty? ( exArrayList.clear(); : exArrayList.clear(); ).

If this is a duplicate, I have not found it with my google keywords.

+8
java garbage-collection android arraylist weak-references
source share
3 answers
  • exArrayList.add(new WeakReference<String>("Hello")); is a bad example because String literals are never gc-ed

  • if it was, for example, exArrayList.add(new WeakReference<Object>(new Object())); , then after GC the object will be GC-ed, but exArrayList.get(0) will still return WeakReference , although exArrayList.get(0).get() will return null

+19
source share

The data exArrayList.get(0) is a WeakReference . It alone is not a weak link, so it will not be compiled ...

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

So,

data.get(0) will not become null , but data.get(0).get() may become.

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

+6
source share

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

0
source share

All Articles