ArrayList> - How to tidy up best?

前端 未结 2 1660
甜味超标
甜味超标 2021-01-05 07:50

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 fast

2条回答
  •  轮回少年
    2021-01-05 08:41

    Here is my take. WeakHashMap removes autmatically, so this should suffice. Beware of hashCode/equals semantics of Runnable though.

    See also Are keySet entries of a WeakHashMap never null? WeakHashMap iteration and garbage collection

    import java.util.WeakHashMap;
    
    public class WeakRunnableList
    {
        private WeakHashMap _items = new WeakHashMap();
    
        public void Add(Runnable r)
        {
            _items.put(r, null);
        }
    
        public void Execute()
        {
            Iterator iterator = _items.keySet().iterator();
            while (iterator.hasNext()) {
                Runnable runnable = iterator.next();
                if (runnable != null) {
                    runnable.run();
                    iterator.remove();
                }
            }
        }
    }
    

提交回复
热议问题