2011-12-21 45 views
6

兩者之間的一個簡單問題:我有一個簡單的WeakRunnableList。 是這種方式可以清理它(刪除死亡引用),還是有一個更優雅和更快的解決方案。我的WeakRunnableList的完整源代碼:ArrayList <WeakReference <Runnable>> - 如何整理最佳?

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

這是我的要求。 WeakHashMap自動刪除,所以這應該就足夠了。不過要小心hashCode/equals的Runnable語義。

又見 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

您在調用item.get()之間存在爭用條件。我將item.get()放入一個局部變量並使用它。

+0

感謝您的評論。其實只是糾正它,會改變後:-) – 2011-12-21 12:25:02

相關問題