views:

24

answers:

1

I have a core JAR that provides some functionality and hence used in lots of other apps as well - desktop apps, web apps etc. Now this core JAR maintains an object pool containing objects that are computationally expensive to create. The object pool is of fixed size and hence I create all of the objects at once and populate the pool. What I want to do is that whenever the app using my JAR is loaded, the object pool is created without the application knowing about the details of such a pool. And that even though the app load time will take a hit because of the pool population, but once the app is past this stage, there shouldn't be any more performance hit in creation of such heavy objects later.

Is there a way to achieve this?

+4  A: 

The only way to do something like this, outside of adding explicit hooks in the client apps to invoke your startup logic is to add static initializers to your classes to construct your pool.

A static initializer is run when your class is first loaded by the JVM (prior to any code in your class being invoked), which is not quite deterministic but is usually when a code path referencing your class is first hit.

I would recommend providing some sort of hooks into your startup logic for the client applications to invoke, this way they can precisely control this type of thing rather than having your startup logic run at an unpredictable time.

matt b
+1 For the final recommendation
Stephen C
You could also do this lazily, using something like the singleton pattern for the static pool. The first time a method is called that relies upon it, the pool could be populated.
andersoj