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
2 Answers 2
It is really the flyweight pattern which is a specialized sort of object pool, where objects get shared to save memory.
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() );
-
3Sounds possible, but do you have timings to support this?user949300– user9493002014年06月23日 03:47:41 +00:00Commented Jun 23, 2014 at 3:47
-
edited answer..misterbiscuit– misterbiscuit2014年06月23日 17:40:47 +00:00Commented Jun 23, 2014 at 17:40
-
1That is a terrible benchmark. Even ignoring that, simply reversing the order of the tests changes the results of the benchmark.awksp– awksp2014年06月24日 00:30:25 +00:00Commented Jun 24, 2014 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?misterbiscuit– misterbiscuit2014年06月24日 04:15:33 +00:00Commented Jun 24, 2014 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 ofNanoStopWatch
), the first one to go always takes between 0.1-0.3 seconds longer to run, whether it is cached or boxed.awksp– awksp2014年06月24日 16:47:05 +00:00Commented Jun 24, 2014 at 16:47