Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayList<WeakReference<Runnable>> - How to tidy up best?

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 faster solution. Full source for my 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);
    }
}
like image 809
Christian Ruppert Avatar asked Dec 21 '11 12:12

Christian Ruppert


People also ask

When to use WeakReference Java?

WeakReference and SoftReference are used when you want to keep something around in case you need it again - but you might not need it and if you do need it you can recreate it.

Why do We use weakreferences?

Weak reference objects, which do not prevent their referents from being made finalizable, finalized, and then reclaimed. Weak references are most often used to implement canonicalizing mappings. Suppose that the garbage collector determines at a certain point in time that an object is weakly reachable.

How are weak references implemented?

When a weak reference A is created to an object B, there would be an entry in the hashtable modified or created, whose key would be the pointer to B. "Dirty" - to store a special hash-value with each object, which would be zeroed when the object is destroyed.


2 Answers

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<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();
            }
        }
    }
}
like image 139
polve Avatar answered Nov 03 '22 00:11

polve


You have a race condition between calls to item.get(). I would place item.get() into a local variable and use that.

like image 43
Peter Lawrey Avatar answered Nov 03 '22 01:11

Peter Lawrey