Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

finding weak reference objects in collections in java

A couple of questions regarding Java's WeakReference and Collections:

  1. 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?

  2. 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.

like image 752
Petriborg Avatar asked Jun 22 '09 13:06

Petriborg


People also ask

What is the use of WeakReference in Java?

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.

When should weak reference be used in garbage collection?

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.

What is a WeakHashMap?

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.

What are weak and soft references in Java?

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.


1 Answers

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.

like image 140
Mr. Shiny and New 安宇 Avatar answered Oct 27 '22 01:10

Mr. Shiny and New 安宇