harmony-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Jimmy,Jing Lv" <firep...@gmail.com>
Subject [Luni][WeakReference]Avoid using strong-referenced objects as keys of WeakHashMap
Date Wed, 28 May 2008 07:47:55 GMT

    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<?>,

    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,

    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