views:

3049

answers:

9

The use of weak references is something that I've never seen an implementation of so I'm trying to figure out what the use case for them is and how the implementation would work. When would you (or have you) had a need to use a WeakHashMap or WeakReference and how would it be used?

+1  A: 

If you for example want to keep track of all objects created of a certain class. To still allow these objects to be garbage collected, you keep a list/map of weak references to the objects instead of the objects themselves.

Now if someone could explain phantom-references to me, I'd be happy...

JesperE
One use: PhantomReferences allow you to determine exactly when an object was removed from memory. They are in fact the only way to determine that.(http://weblogs.java.net/blog/enicholas/archive/2006/05/understanding_w.html)
Jacob
+18  A: 

One problem with strong references is caching, particular with very large structures like images. Suppose you have an application which has to work with user-supplied images, like the web site design tool I work on. Naturally you want to cache these images, because loading them from disk is very expensive and you want to avoid the possibility of having two copies of the (potentially gigantic) image in memory at once.

Because an image cache is supposed to prevent us from reloading images when we don't absolutely need to, you will quickly realize that the cache should always contain a reference to any image which is already in memory. With ordinary strong references, though, that reference itself will force the image to remain in memory, which requires you to somehow determine when the image is no longer needed in memory and remove it from the cache, so that it becomes eligible for garbage collection. You are forced to duplicate the behavior of the garbage collector and manually determine whether or not an object should be in memory.

Understanding Weak References, Ethan Nicholas

Jacob
Wouldn't SoftReferences be better in this case, i.e. references which are only collected when memory starts running out.
JesperE
I agree with JesperE
Marcio Aguiar
A: 

One real world use I had for WeakReferences is if you have a single, very large object that's rarely used. You don't want to keep it in memory when it's not needed; but, if another thread needs the same object, you don't want two of them in memory either. You can keep a weak reference to the object somewhere, and hard references in the methods that use it; when the methods both finish, the object will be collected.

A: 

you can use weakhashmap to implement a resource-free caching for expansive object creation.

but note that it is not desireable to have mutable objects. i used it to cache query results (which take about 400 ms to execute) to a text-search engine, which is rarely updated.

Andreas Petersson
A: 

I did a google code search for "new WeakHashMap()".

I got a bunch of matches from the GNU classpath project and
2) Apache Geronimo Project : WeakHashMapEditor.java

3) Apache Lucene project : http://www.google.com/codesearch?hl=en&q=lang:java+new+WeakHashMap+show:aL7OOwfe6ug:uTvt_O6VOmg:aL7OOwfe6ug&sa=N&cd=9&ct=rc&cs_p=http://svn.apache.org/repos/asf/lucene/java/&cs_f=trunk/src/java/org/apache/lucene/search/CachingWrapperFilter.java

anjanb
+1  A: 

This blog post demonstrates the use of both classes: Java: synchronizing on an ID. The usage goes something like this:

private static IdMutexProvider MUTEX_PROVIDER = new IdMutexProvider();

public void performTask(String resourceId) {
 IdMutexProvider.Mutex mutext = MUTEX_PROVIDER.getMutex(resourceId);
 synchronized (mutext) {
  // look up the resource and do something with it
 }
}

IdMutextProvider provides id-based objects to synchronize on. The requirements are:

  • must return a reference to the same object for concurrent use of equivalent IDs
  • must return a different object for different IDs
  • no release mechanism (objects are not returned to the provider)
  • must not leak (unused objects are eligible for garbage collection)

This is achieved using an internal storage map of type:

WeakHashMap<Mutex, WeakReference<Mutex>>

The object is both key and value. When nothing external to the map has a hard reference to the object, it can be garbage collected. Values in the map are stored with hard references, so the value must be wrapped in a WeakReference to prevent a memory leak. This last point is covered in the javadoc.

McDowell
+7  A: 

One distinction to be clear on is the difference between a WeakReference and a SoftReference.

Basically a WeakReference will be GC-d by the JVM eagerly, once the referenced object has no hard references to it. A SoftReferenced object on the other hand, will tend to be left about by the garbage collector until it really needs to reclaim the memory.

A cache where the values are held inside WeakReferences would be pretty useless (in a WeakHashMap, it is the keys which are weakly referenced). SoftReferences are useful to wrap the values around when you want to implement a cache which can grow and shrink with the available memory

oxbow_lakes
+1  A: 

As stated above, weak reference are held as long as a strong reference exists.

An example usage would be to use WeakReference inside listeners, so that the listeners are no longer active once the main reference to their target object is gone. Note that this does not mean the WeakReference is removed from the listeners list, cleaning up is still required but can be performed, for example, at scheduled times. This has also the effect of preventing the object listened to from holding strong references and eventually be a source of memory bloat. Example: Swing GUI components refering a model having a longer lifecycle than the window.

While playing with listeners as described above we rapidly realised that objects get collected "immediately" from a user's point of view.

Louis Jacomet
A: 

One Common use of WeakReferences and WeakHashMaps in particular is for adding properties to objects. Occasionally you want to add some functionality or data to an object but subclassing and/or composition are not an option in that case the obvious thing to do would be to create a hashmap linking the object you want to extend to the property you want to add. then whenever you need the property you can just look it up in the map. However, if the objects you are adding properties to tend to get destroyed and created a lot, you can end up with a lot of old objects in your map taking up a lot of memory

if you use a WeakHashMap instead the objects will leave your map as soon as they are no longer used by the rest of your program, which is the desired behavior.

I had to do this to add some data to java.awt.Component to get around a change in the JRE between 1.4.2 and 1.5, I could have fixed it by subclassing every component i was interested int (JButton, JFrame, JPanel....) but this was much easier with much less code.

luke