的ArrayList<&的WeakReference LT;可运行>> - 如何整理好? [英] ArrayList<WeakReference<Runnable>> - How to tidy up best?
本文介绍了的ArrayList<&的WeakReference LT;可运行>> - 如何整理好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
之间的一个简单问题:我有一个简单的WeakRunnableList。
这样可以清理它(删除死引用),还是有一个更优雅,更快的解决方案。我的WeakRunnableList的完整源代码:
A quick question in between: I have a simple WeakRunnableList. Is this way ok to clean it up (removing dead references), or is there a more elegant and faster 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);
}
}
推荐答案
这里是我的。
WeakHashMap自动删除,所以这应该足够了。请注意Runnable的hashCode / equals语义。
Here is my take. WeakHashMap removes autmatically, so this should suffice. Beware of hashCode/equals semantics of Runnable though.
另见
WeakHashMap的keySet条目永远不会为空吗?
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();
}
}
}
}
这篇关于的ArrayList<&的WeakReference LT;可运行>> - 如何整理好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文