2011-12-21 37 views
6

Một câu hỏi nhanh ở giữa: Tôi có một WeakRunnableList đơn giản. Là cách này ok để làm sạch nó lên (loại bỏ tham chiếu chết), hoặc là có một giải pháp thanh lịch hơn và nhanh hơn. Nguồn đầy đủ cho WeakRunnableList của tôi:ArrayList <WeakReference <Runnable>> - Làm thế nào để dọn dẹp tốt nhất?

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

Trả lời

6

Đây là của tôi. WeakHashMap loại bỏ tự động, vì vậy điều này là đủ. Hãy coi chừng hashCode/bằng ngữ nghĩa của Runnable.

Xem thêm 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

Bạn có điều kiện cuộc gọi giữa các cuộc gọi đến item.get(). Tôi sẽ đặt item.get() vào một biến cục bộ và sử dụng nó.

+0

Cảm ơn đã nhận xét. Trên thực tế chỉ cần sửa chữa nó, sẽ thay đổi trong bài :-) –

Các vấn đề liên quan