Skip to main content
Blog

Using a Pool to control resource intensive processes

By 18 juli 2013januari 30th, 2017No Comments

This article gives an example of how you can use a Pool to limit resource usage.

In big web applications it is essential to put limits on how much resources a specific process can use. For example, if you use BIRT embedded in your application you might want to restrict the number of reports being run at the same time. Especially if you expose reports to end users creating and running reports on the fly.

Pools are often used for recycling objects that are expensive to create. But they can also be used to limit the number of instantiations of certain objects. In the BIRT example I would like to control the number of Engines. For that, I use the Apache Commons Pool:

public class ReportUtil {
    private static final int POOL_SIZE = 10;
    private static final PoolableObjectFactory POOLABLE_OBJECT_FACTORY = new PoolableObjectFactory() {
        @Override
        public boolean validateObject(Object object) {
            return true;
        }

        @Override
        public void passivateObject(Object object) throws Exception {
        }

        @Override
        public Object makeObject() throws Exception {
            IReportEngineFactory factory =
                    (IReportEngineFactory) Platform
                            .createFactoryObject(IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY);
            return factory.createReportEngine(CONFIG);
        }

        @Override
        public void destroyObject(Object object) throws Exception {
            IReportEngine engine = (IReportEngine) object;
            engine.destroy();
        }

        @Override
        public void activateObject(Object object) throws Exception {
        }
    };

    private static final GenericObjectPool ENGINE_POOL = new GenericObjectPool(POOLABLE_OBJECT_FACTORY,
            POOL_SIZE);

}

And whenever I need an BIRT Engine, I can simply use something like this:

public IReportEngine getEngine() {
        return (IReportEngine) ENGINE_POOL.borrowObject();
    }

Some references: