harmony-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Alexey Varlamov" <alexey.v.varla...@gmail.com>
Subject Re: [Luni][WeakReference]Avoid using strong-referenced objects as keys of WeakHashMap
Date Wed, 28 May 2008 10:17:50 GMT
Generally speaking, using WeakReference for caching is just wrong -
cache entry will be removed as long as it's key has no more strong
references thus such cache does not fulfil it's destination.
SoftReference is more sensible for implementing caches as it will
survive until memory is short (well, AFAIR drlvm does not obey this
contract yet).

FYI, there is handy org.apache.harmony.luni.util.ThreadLocalCache
which also should help to avoid synchronization overhead.


2008/5/28, Jimmy,Jing Lv <firepure@gmail.com>:
> Hi,
>    I see a memory leak using Harmony Beans, looking into heap there
> are many objects of WeakHashMap.Entry, and in hours they were never
> GCed. And at last I find it was in java.beans.Introspector,  using a
> WeakHashMap as a cache:
>    private static Map<Class<?>, StandardBeanInfo> theCache =
> Collections.synchronizedMap(new WeakHashMap<Class<?>,
> StandardBeanInfo>(DEFAULT_CAPACITY));
>    Unfortunately, we see it uses Class objects as WeakHashMap.Entry
> key, which is always referenced by vm (only can be GCed when a class
> is unloaded).  but WeakHashMap.Entry extends
> java.lang.ref.WeakReference, which requires a weak reference as its
> key, as a result, using Class object shall always keep Entries in
> heap, cause a memory in that way.
>    A quick search I also find in java.util.ResourceBundle, it defines
> its cache as:
>    private static final WeakHashMap<Object, Hashtable<String,
> ResourceBundle>> cache = new WeakHashMap<Object, Hashtable<String,
> ResourceBundle>>();
>    and in code it uses ClassLoader objects as key.
>    However as we know, ClassLoader objects are handled by vm as well
> and may not be released, this as well may cause memory leak.
>    I suggest if we want to use WeakHashMap(and don't want to cause a
> memory leak), we may set its key carefully and avoid using objects
> that are referenced in other area (especially vm) that we can not
> handle, like Class, etc. And I have a a little approach for String
> objects, we know they are handled by vm with a pool, so directly use
> String as key seems  also cause a leak, however if we put it into
> WeakHashMap as:
>     WeakHashMap.put(new String(oldString), valueObject);
>    Run a few minutes I see no leak. Maybe some VM guru can tell us
> what's going on with the string pool do in VM?
>    To fix these 2 problem, I suggest create a new inner class and use
> it as Key of WeakHashMap (don't know if "new String(oldString)" should
> work? ).
>    And anyone saw the same problem in Harmony code? Any
> comments/suggests? Thanks!
> --
> Best Regards!
> Jimmy, Jing Lv
> China Software Development Lab, IBM

View raw message