Women in Technology

Hear us Roar



Article:
  Memoization in Java Using Dynamic Proxy Classes
Subject:   Methods as Keys
Date:   2003-08-21 23:47:57
From:   anonymous2
Nice article. It's a very nice use of dynamic proxies to separate concerns. One thing you may wish to consider as part of your "fully featured version of Memoizer" is a WeakHashMap for your top-level map that maps Method instances to value caches. Using a "standard" map implementation will prevent the JVM from unloading any class that has a method as a key in your top-level map.


Alternatively, if you want to allow the JVM to unload classes but keep cached values for a method, you could use the fully-qualified "mangled" method names as the keys.


Of course, as long as you keep a reference to the dynamic proxy, you keep a reference to an instance of a class, which means the class wouldn't be a candidate for garbage collection anyway.


Just something to think about.


-- Chuck

Full Threads Newest First

Showing messages 1 through 2 of 2.

  • Tom White photo Methods as Keys
    2003-08-22 00:08:51  Tom White | O'Reilly Author [View]

    Thanks for your comments. It is definitely worth considering garbage collection of classes. As you point out, keeping a "standard" map whose keys are Method objects will prevent the Class instance that owns the method from being garbage collected since a Method has a reference to its owning Class.

    Using a WeakHashMap is a good idea, and probably the best way to go. By "mangling" a method name, do you mean including the method's parameter types (a bit like the toString() on Method)? The drawback with this approach is that you have to reconstruct (or retrieve from a cache) the Method each time it is invoked.

    Tom
    • Methods as Keys
      2003-08-22 08:35:05  crazybob [View]

      You can store SoftReferences to the cached values and remove a key when it's value gets collected (using a ReferenceQueue).

      One more note, arrays as method arguments. Rather than using Arrays.asList(), I use a class I wrote called ArrayObject (http://crazybob.org/downloads/ArrayObject.java). Basically, it just implements equals() and hashCode() for arrays. It also compares nested arrays, which is why it works for array arguments.