中间有一个简单的问题:我有一个简单的 WeakRunnableList。 是否可以通过这种方式清理它(删除死引用),或者是否有更优雅、更快速的解决方案。我的 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);
}
}
最佳答案
这是我的看法。 WeakHashMap 自动删除,所以这应该足够了。不过要注意 Runnable 的 hashCode/equals 语义。
另见 Are keySet entries of a WeakHashMap never null? WeakHashMap iteration and garbage collection
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();
}
}
}
}
关于java - ArrayList<WeakReference<Runnable>> - 如何最好地整理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8589581/