Is it possible to create a pool of objects similar to a string?

since jvm manages the string pool for String, from which it searches for any new string assignment, similarly, can we create a pool of any other object or primitives?

+5
source share
2 answers

The internal pool for Java constant constants is what the Java compiler knows, so you cannot accurately simulate the exact behavior.

The pool itself is nothing but a hash map. If your object has a suitable identifier, you can, of course, merge the pool for your own objects: just create a static method that takes the key, looks at it in the static hash map and builds a new object only if it has not been merged yet. Note, however, that in orde, for this simple working scheme, it is important that your object is immutable.

+4
source

The string pool is not the only pool / cache in Java, Integer and other wrapper classes use the cache, you can look at the source code of Integer as an example

public static Integer valueOf(int i) {
    assert IntegerCache.high >= 127;
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}

you can also take a look at http://commons.apache.org/proper/commons-pool//

+3
source

All Articles