java - ArrayList<WeakReference<Runnable>> - 如何最好地整理?

标签 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);
    }
}

最佳答案

这是我的看法。 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/

相关文章:

java - spring-ws:让 EchoEndpoint 工作,而不是返回 404

ios - 为什么初始化为 `weak` 在 Swift 中返回 `nil`?

python - 为什么我的 weakrefs 在指向一个方法时死在水中?

python - 为什么 weakref 不支持 Python 中的内置类型?

java - linux下如何设置路径?

java - java中的通用容器

java - 如何从java中给定的 map 值查找最新日期

java - 将 byte[] 与 spring-rest 和 springfox 一起使用

c# - 如果执行关闭操作,WeakAction中的错误

python - WeakValueDictionary 保留对没有更多强引用的对象的引用