ArrayList <WeakReference <Runnable>> - What is the best way to tidy up?

A quick question between them: I have a simple WeakRunnableList. Is this way to clear it (removing dead links), or there is a more elegant and quick solution. Full source for my WeakRunnableList:

public class WeakRunnableList { private ArrayList<WeakReference<Runnable>> _items = new ArrayList<WeakReference<Runnable>>(); public void Add(Runnable r) { _items.add(new WeakReference<Runnable>(r)); } public void Execute() { ArrayList<WeakReference<Runnable>> remove = new ArrayList<WeakReference<Runnable>>(); for (WeakReference<Runnable> item : _items) { Runnable tempCheck = item.get(); if (tempCheck == null) { remove.add(item); } else { tempCheck.run(); } } _items.removeAll(remove); } } 
+6
source share
2 answers

Here is my welcome. WeakHashMap is automatically deleted, so this should be enough. Beware of hashCode / equals Runnable semantics.

See also. Are KeySet entries of the WeakHashMap file involved? Iterating and garbage collection WeakHashMap

 import java.util.WeakHashMap; public class WeakRunnableList { private WeakHashMap<Runnable, Void> _items = new WeakHashMap<Runnable, Void>(); public void Add(Runnable r) { _items.put(r, null); } public void Execute() { Iterator<Runnable> iterator = _items.keySet().iterator(); while (iterator.hasNext()) { Runnable runnable = iterator.next(); if (runnable != null) { runnable.run(); iterator.remove(); } } } } 
+6
source

You have a race condition between calls to item.get (). I would put item.get () in a local variable and use it.

+1
source

Source: https://habr.com/ru/post/904235/


All Articles