Page 138
Optimization 37: Object Pools The previous optimization was made simple by the fact that we knew in advance that we needed only a single Vector object in the course of the computation. If you know in advance that you need only one instance of a resource that is used repeatedly, you could recycle and reuse that same instance over and over. This is actually a degenerate case in which the pool size is 1. In the more general scenario, you don’t necessarily have advance knowledge of how many instances are required. It could be 0, 1, or many. In that case, you may have to acquire the resources on the fly but you still want to avoid the cost of creating and destroying expensive resources on a regular basis. The answer here is pooling. After a brief transient state of populating the pool, acquiring and releasing the pooled resource is significantly cheaper because acquire and release operations do not really equate to expensive create and destroy. We merely put and get to and from the pool. Resources that often get pooled are threads, JDBC connections, persistent sockets, as well as other user-defined heavyweight objects. The following code is a rudimentary object pool: public class ObjectPool { protected Object objects[]; protected Class cls; protected int head; public ObjectPool(String className, int size) throws ClassNotFoundException, IllegalArgumentException { this(Class.forName(className), size); } private ObjectPool(Class p_class, int size) throws IllegalArgumentException { if((null == p_class) || (size <= 0)) { throw new IllegalArgumentException("Invalid arguments"); } head = 0; cls = p_class; objects = new Object[size]; } public Object getObjectFromPool() throws InstantiationException, IllegalAccessException { Object obj = null; synchronized(this) { // If there is an available object in // the pool, then return it. Else, create // a new instance of the class and return it. if (head > 0) { head–; obj = objects[head]; objects[head] = null; } else { obj = (Object)cls.newInstance(); } Page 139
Hint: If you are looking for very good and affordable webspace to host and run your java hosting application check Virtualwebstudio java web hosting provider