的ArrayList <WeakReference的<可运行>&GT; - 如何整理好?</weakreference <runnable>

时间:2011-12-21 12:08:51

标签: java weak-references

之间的一个简单问题:我有一个简单的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);
    }
}

2 个答案:

答案 0 :(得分:7)

这是我的看法。 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();
            }
        }
    }
}

答案 1 :(得分:1)

您对item.get()的调用之间存在竞争条件。我会将item.get()放入一个局部变量并使用它。