All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.cg.eventbus.producer.PooledEventProducerFactory Maven / Gradle / Ivy

There is a newer version: 1.0.8
Show newest version
/**
 * 
 */
package org.cg.eventbus.producer;

import java.lang.reflect.Constructor;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.log4j.Logger;

/**
 * @author yanlinwang, liang.li
 *
 */
public class PooledEventProducerFactory  extends BasePooledObjectFactory< AbstractEventProducer> {
	
	private static final Logger logger = Logger.getLogger(PooledEventProducerFactory.class);
	
	private Configuration producerConf;
	private AtomicInteger count = new AtomicInteger(0);
	private Class poolType;
	private Constructor pooledConstructor;
		
	public PooledEventProducerFactory (Class poolType, String fileName) 
			throws ConfigurationException {
		this(poolType,new PropertiesConfiguration(fileName));
	}
	
	public PooledEventProducerFactory (Class poolType, Configuration config) {
		this.poolType = poolType;
		producerConf = config;
		try {
			pooledConstructor = poolType.getConstructor(Configuration.class);
		} catch (Exception e) {
			logger.error("failed to get pooled object constructor", e);
		} 
		
	}
	
	@Override
	public AbstractEventProducer create() throws Exception {
		
		AbstractEventProducer producer = ( AbstractEventProducer ) pooledConstructor.newInstance(new Object[]{producerConf});
		logger.info("Number of producer created " + count.addAndGet(1));
		return producer;
	}

	@Override
	public PooledObject> wrap(
			AbstractEventProducer provider) {
		return new DefaultPooledObject>(provider);
	}

	@Override
	public void destroyObject(PooledObject> p) {
		p.getObject().close();
	}
	       
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy