When would you use a WeakHashMap or a WeakReferenc

2019-01-02 16:40发布

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 have you needed to use a WeakHashMap or WeakReference and how was it used?

10条回答
听够珍惜
2楼-- · 2019-01-02 17:17

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.

查看更多
临风纵饮
3楼-- · 2019-01-02 17:18

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.

查看更多
深知你不懂我心
4楼-- · 2019-01-02 17:19

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

I got a bunch of matches from the GNU classpath project and

  1. Apache xbean Project : WeakHashMapEditor.java
  2. Apache Lucene project : CachingWrapperFilter.java
查看更多
临风纵饮
5楼-- · 2019-01-02 17:24

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.

查看更多
登录 后发表回答