commons-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Rich Dougherty <>
Subject Re: [lang] Pooled and mutable numbers.
Date Tue, 11 Mar 2003 23:31:26 GMT
>1) A mechanism for pooling Integers, Floats, Doubles, etc. as they are
>created, to conserve memory.  For example, instead of having:
>new Integer(1)
>scattered throughout the code, there could be a NumberPool class which
>would allow:
>the values would be cached, and could use a WeakHashMap or something
>similar to manage the cache.

Here's a fun little class. It is inspired by the String.intern() method.

import java.util.WeakHashMap;
import java.util.Map;

public class Interner {

     private Map internedObjects = new WeakHashMap();

     public Interner() {

     public Object intern(Object object) {
         Object internedObject = internedObjects.get(object);
         if (internedObject == null) {
             internedObjects.put(object, object);
             return object;
         } else {
             return internedObject;


The overhead of memory overhead of the WeakHashMap would have to be 
carefully considered before it is used to save memory. Also, it requires 
an object to be created before it can be interned (even if that object 
is garbage collected right after it is interned), so it doesn't really 
reduce the amount of object creation.

Still, it can be handy since it allows you to perform comparisons based 
on reference.

   interner.intern(new Integer(x)) == interner.intern(new Integer(x))

And if you had enough objects that were equal(), it could still save you 


View raw message