A couple of questions regarding Java's WeakReference and Collections:
Is there a library out there that implements Java's various data-set interfaces (eg Collection, List, Set, Queue etc) with WeakReference transparently? Like WeakHashMap is for the HashMap interface?
Or is the common solution to simply create normal Collections and then use some sort of trick with compareTo or a Comparator or something to make searching the collection work correctly?
I basically would like this:
public interface WeakCollection<E> extends Collection<E> {}
But the contract for the interface is that the references to E are stored weakly. Obviously I do not have a problem with get(int index)
returning null when that object has gone away etc, but I would like the contains(E e)
function and other items like it to work properly.
I'm just trying to avoid the "not invented here" trap and ensuring that if I do implement this myself that its the simplest solution possible.
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.
A weak reference permits the garbage collector to collect the object while still allowing the application to access the object. A weak reference is valid only during the indeterminate amount of time until the object is collected when no strong references exist.
Simply put, the WeakHashMap is a hashtable-based implementation of the Map interface, with keys that are of a WeakReference type. An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use, meaning that there is no single Reference that point to that key.
A Soft reference is eligible for collection by garbage collector, but probably won't be collected until its memory is needed. i.e. garbage collects before OutOfMemoryError . A Weak reference is a reference that does not protect a referenced object from collection by GC.
JBoss has a WeakSet. In Java 6, you can also do
Set<T> s = Collections.newSetFromMap(new WeakHashMap<T, Boolean>());
Also I found a WeakArrayList that's LGPL if that helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With