Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it possible to create object pool similar to string?

Tags:

java

as jvm manages string pool for String from which it looks up for any new String assignment, similarly, can we develop a pool of any other object or primitives?

like image 378
Ankit Avatar asked Mar 15 '13 10:03

Ankit


2 Answers

The interning pool for Java String constants is something known to the Java compiler, so you cannot mimic the exact behavior by yourself.

The pool itself, however, is nothing more than a hash map. If your object has a suitable identifier, you can certainly roll a pool for your own objects: simply create a static method that takes a key, looks it up in a static hash map, and builds a new object only if it has not been pooled yet. Note, however, that in orde for this simple scheme to work, it is essential for your object to be immutable.

like image 191
Sergey Kalinichenko Avatar answered Oct 15 '22 10:10

Sergey Kalinichenko


String pool is not the only pool / cache in Java, Integer and other wrapper classes use cache, you can take a look at the Integer source code 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//

like image 34
Evgeniy Dorofeev Avatar answered Oct 15 '22 10:10

Evgeniy Dorofeev