3

One of the best-known examples of a full-fledged object pool is the JDBC connection pool. Main reasons:

  • objects in the pool are expensive to create and relate with external resources
  • each object in the pool is served to at most one client a time
  • objects in the pool need to be brought back to a clean state before being served again to a new client

With the above in mind, can the Java Integer cache be regarded as a object pool realization? Here is why I doubt it:

  • objects in the pool can be used by more than one client a time due to their immutability
  • immutability also prevents pool objects from reaching a stale state
  • there's no notion of a "free" object, ready to be allocated to a client
6

It is really the flyweight pattern which is a specialized sort of object pool, where objects get shared to save memory.

-2

The problem with a Java Integer cache is that the VM is optimized for boxing/unboxing. The lookup mechanism for a "cached" Java Integer is going to be more expensive than just creating the object.

building cache
test length 500,000,000
cached duration: 12001.345937
boxed duration: 12108.983383

In many scenarios the lookup using many threads is going to cause lots of cache misses across different cores and have more of a performance hit.

System.out.println("building cache");

Integer[] cache = new Integer[50000];

for( int i = 0; i < cache.length; i ++)
{
    cache[i] = new Integer(i);
}

int c = 500 * 1000000;
int t = 0;

System.out.println("test length " + c );

NanoStopWatch watch = new NanoStopWatch();

watch.start();

while( t < c)
{
    Integer p = cache[ (int)  (Math.random() * 5000) ];

    t++;
}

watch.stop();

System.out.println("cached duration: " + watch.duration() );

t = 0;

watch.start();

while( t < c)
{
    Integer p =  (Integer) (int) (Math.random() * 5000);

    t++;
}

watch.stop();

System.out.println("boxed duration: " + watch.duration() );
  • 3
    Sounds possible, but do you have timings to support this? – user949300 Jun 23 '14 at 3:47
  • edited answer.. – lots of crisps Jun 23 '14 at 17:40
  • 1
    That is a terrible benchmark. Even ignoring that, simply reversing the order of the tests changes the results of the benchmark. – awksp Jun 24 '14 at 0:30
  • numbers are the same every time within .01% forwards and backwards - maybe if you could explain a better way to test this? – lots of crisps Jun 24 '14 at 4:15
  • Are you saying that you get the same results when you swap the order? When I run the benchmark (had to use System.nanoTime() instead of NanoStopWatch), the first one to go always takes between 0.1-0.3 seconds longer to run, whether it is cached or boxed. – awksp Jun 24 '14 at 16:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.