Hi all,

    Just a small comment on HashMaps with weak values:

Jeremias Maerki <[EMAIL PROTECTED]> wrote on 07/13/2006 04:43:07 PM:

> Ok, so I changed the WeakHashMap to a HashMap and wrapped the values in
> WeakReferences. Tadaaa! A PDF with 182 JPEG images with a total size of
> 258 MB is suddenly produced without exceptions using the VM's default
> heap settings, never going beyond 26MB heap usage. *g*

   There is a potential problem with this approach that Batik ran into.
Unless you go a little further those weak values accumulate in the map. 
In your case this probably isn't a big deal, but for Batik where there
are potentially of thousands (or tens of thousands, think mouse move 
events) 
of entries, these 'dead' entries start to add up.

   As a result Batik has batik.util.CleanerThread.  This class has
inner classes that subclass the various SoftReference classes with an 
additional method 'public void cleared()'.  This method is called by
the CleanerThread when the object the soft reference is point at is
cleared from memory (it uses the ReferenceQueue part of soft references).

   This gives you the hook you need to then de-register the entry from
the has table.  This is actually an incredibly useful 'addition' to
the standard soft reference classes (for example I will often use
it to check if classes I think should go to GC really do go to GC).

   I should also mention that Batik has a class called 
'SoftReferenceCache'
which is a thread safe implementation of exactly what you just 
implemented. 
The interface may seem a little odd but it is designed to ensure that
only one party ever has to decode a resource even if multiple threads
request it "at the same time".

   Anyway just thought I would add my 2 cents...

Reply via email to