Example usage for org.apache.commons.pool.impl GenericObjectPool GenericObjectPool

List of usage examples for org.apache.commons.pool.impl GenericObjectPool GenericObjectPool

Introduction

In this page you can find the example usage for org.apache.commons.pool.impl GenericObjectPool GenericObjectPool.

Prototype

public GenericObjectPool(PoolableObjectFactory factory) 

Source Link

Document

Create a new GenericObjectPool using the specified factory.

Usage

From source file:edu.illinois.enforcemop.examples.apache.pool.TestGenericObjectPool.java

public void testEvictionSoftMinIdle() throws Exception {
    GenericObjectPool pool = null;/* w ww . j  a  v a  2  s  .c  om*/

    class TimeTest extends BasePoolableObjectFactory {
        private final long createTime;

        public TimeTest() {
            createTime = System.currentTimeMillis();
        }

        public Object makeObject() throws Exception {
            return new TimeTest();
        }

        public long getCreateTime() {
            return createTime;
        }
    }

    pool = new GenericObjectPool(new TimeTest());

    pool.setMaxIdle(5);
    pool.setMaxActive(5);
    pool.setNumTestsPerEvictionRun(5);
    pool.setMinEvictableIdleTimeMillis(3000L);
    pool.setSoftMinEvictableIdleTimeMillis(1000L);
    pool.setMinIdle(2);

    Object[] active = new Object[5];
    Long[] creationTime = new Long[5];
    for (int i = 0; i < 5; i++) {
        active[i] = pool.borrowObject();
        creationTime[i] = new Long(((TimeTest) active[i]).getCreateTime());
    }

    for (int i = 0; i < 5; i++) {
        pool.returnObject(active[i]);
    }

    // Soft evict all but minIdle(2)
    Thread.sleep(1500L);
    pool.evict();
    assertEquals("Idle count different than expected.", 2, pool.getNumIdle());

    // Hard evict the rest.
    Thread.sleep(2000L);
    pool.evict();
    assertEquals("Idle count different than expected.", 0, pool.getNumIdle());
}

From source file:edu.illinois.enforcemop.examples.apache.pool.TestGenericObjectPool.java

/**
 * Verifies that maxActive is not exceeded when factory destroyObject has high
 * latency, testOnReturn is set and there is high incidence of validation
 * failures.//from  www  .j  av a2  s  . c  om
 */
public void testMaxActiveInvariant() throws Exception {
    int maxActive = 15;
    SimpleFactory factory = new SimpleFactory();
    factory.setEvenValid(false); // Every other validation fails
    factory.setDestroyLatency(100); // Destroy takes 100 ms
    factory.setMaxActive(maxActive); // (makes - destroys) bound
    factory.setValidationEnabled(true);
    pool = new GenericObjectPool(factory);
    pool.setMaxActive(maxActive);
    pool.setMaxIdle(-1);
    pool.setTestOnReturn(true);
    pool.setMaxWait(1000L);
    runTestThreads(5, 10, 50);
}

From source file:edu.illinois.enforcemop.examples.apache.pool.TestGenericObjectPool.java

public void testMaxWaitMultiThreaded() throws Exception {
    final long maxWait = 500; // wait for connection
    final long holdTime = 2 * maxWait; // how long to hold connection
    final int threads = 10; // number of threads to grab the object initially
    SimpleFactory factory = new SimpleFactory();
    GenericObjectPool pool = new GenericObjectPool(factory);
    pool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_BLOCK);
    pool.setMaxWait(maxWait);//  w  w  w .jav  a 2s.c  o  m
    pool.setMaxActive(threads);
    // Create enough threads so half the threads will have to wait
    WaitingTestThread wtt[] = new WaitingTestThread[threads * 2];
    for (int i = 0; i < wtt.length; i++) {
        wtt[i] = new WaitingTestThread(pool, holdTime);
    }
    long origin = System.currentTimeMillis() - 1000;
    for (int i = 0; i < wtt.length; i++) {
        wtt[i].start();
    }
    int failed = 0;
    for (int i = 0; i < wtt.length; i++) {
        wtt[i].join();
        if (wtt[i]._thrown != null) {
            failed++;
        }
    }
    if (DISPLAY_THREAD_DETAILS || wtt.length / 2 != failed) {
        System.out.println("MaxWait: " + maxWait + " HoldTime: " + holdTime + " MaxActive: " + threads
                + " Threads: " + wtt.length + " Failed: " + failed);
        for (int i = 0; i < wtt.length; i++) {
            WaitingTestThread wt = wtt[i];
            System.out.println("Preborrow: " + (wt.preborrow - origin) + " Postborrow: "
                    + (wt.postborrow != 0 ? wt.postborrow - origin : -1) + " BorrowTime: "
                    + (wt.postborrow != 0 ? wt.postborrow - wt.preborrow : -1) + " PostReturn: "
                    + (wt.postreturn != 0 ? wt.postreturn - origin : -1) + " Ended: " + (wt.ended - origin)
                    + " ObjId: " + wt.objectId);
        }
    }
    assertEquals("Expected half the threads to fail", wtt.length / 2, failed);
}

From source file:oauth.OAuthTokenValdiator.java

private OAuthTokenValdiator() {
    try {//from w  w w  .  j a  v a2s .co m
        Properties properties = getWebSocketConfig();
        this.stubs = new GenericObjectPool(new OAuthTokenValidaterStubFactory(properties));
    } catch (IOException e) {
        log.error("Failed to parse the web socket config file " + WEBSOCKET_CONFIG_LOCATION);
    }
}

From source file:org.aitools.util.db.DBConnectionManager.java

/**
 * Create a new database connection manager using the given driver (classname)
 * and database URI (DBMS-specific)./*  ww w  .j  a  va2  s .  c o m*/
 * 
 * @param logger
 * @param driver
 * @param uri
 * @param username
 * @param password
 * @param minIdle
 * @param maxActive
 */
public DBConnectionManager(String driver, String uri, String username, String password, int minIdle,
        int maxActive) {

    Classes.verifyAvailable(driver, "database driver");

    GenericObjectPool connectionPool = new GenericObjectPool(null);
    connectionPool.setMinIdle(minIdle);
    connectionPool.setMaxActive(maxActive);

    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(uri, username, password);

    @SuppressWarnings("unused")
    PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,
            connectionPool, null, null, false, true);

    this._dataSource = new PoolingDataSource(connectionPool);

    // Was using DdlUtils here, but it did not correctly work for all column properties.
    //this.checkDBSchema();
}

From source file:org.alinous.plugin.mysql.MySQLDataSource.java

public void init(AlinousCore core) throws DataSourceException {
    this.logger = core.getLogger();

    try {/*from  w w  w  . jav  a 2s . c o m*/
        this.driver = MySQLDriverSingleton.getDriver(core);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
        throw new DataSourceException(e);
    } catch (InstantiationException e) {
        throw new DataSourceException(e);
    } catch (IllegalAccessException e) {
        throw new DataSourceException(e);
    } catch (Throwable e) {
        throw new DataSourceException(e);
    }

    this.factory = new MySQLConnectionFactory(this.driver, this.user, this.pass, this.uri);
    this.connectionPool = new GenericObjectPool(this.factory);
    this.connectionPool.setMaxActive(32);
    this.connectionPool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_BLOCK);
    this.connectionPool.setTestOnBorrow(true);
    this.connectionPool.setMinEvictableIdleTimeMillis(1000 * 60 * 5);

    this.typeHelper = new TypeHelper(this);

    this.core = core;
}

From source file:org.apache.avalon.dbcp.DbcpConnectionManager.java

/**
 * Creates an <code>GenericObjectPool</code> instance that serves
 * as a the actual pool of connections./* www.  j  a v a 2  s.c  o  m*/
 * 
 * @return <code>GenericObjectPool</code> instance.
 */
private ObjectPool createObjectPool() {
    ObjectPool pool = null;

    // We'll need a ObjectPool that serves as the actual pool
    // of connections.  We'll use a GenericObjectPool instance.
    if (m_pool == null) {
        pool = new GenericObjectPool(null);
    } else {
        pool = new GenericObjectPool(null, getPoolConfig());
    }
    return pool;
}

From source file:org.apache.camel.component.sjms.jms.ConnectionFactoryResource.java

public ConnectionFactoryResource(int poolSize, ConnectionFactory connectionFactory, String username,
        String password, String connectionId, long maxWait) {
    this.connectionFactory = connectionFactory;
    this.username = username;
    this.password = password;
    this.clientId = connectionId;
    this.connections = new GenericObjectPool<Connection>(this);
    this.connections.setMaxWait(maxWait);
    this.connections.setMaxActive(poolSize);
    this.connections.setMaxIdle(poolSize);
    this.connections.setMinIdle(poolSize);
    this.connections.setLifo(false);
}

From source file:org.apache.camel.component.sjms.producer.InOutProducer.java

@Override
protected void doStart() throws Exception {
    if (ObjectHelper.isEmpty(getNamedReplyTo())) {
        log.debug("No reply to destination is defined.  Using temporary destinations.");
    } else {/*from ww  w .  j a v a2 s  . c o m*/
        log.debug("Using {} as the reply to destination.", getNamedReplyTo());
    }
    if (getConsumers() == null) {
        setConsumers(new GenericObjectPool<MessageConsumerResources>(new MessageConsumerResourcesFactory()));
        getConsumers().setMaxActive(getConsumerCount());
        getConsumers().setMaxIdle(getConsumerCount());
        while (getConsumers().getNumIdle() < getConsumers().getMaxIdle()) {
            getConsumers().addObject();
        }
    }
    super.doStart();
}

From source file:org.apache.camel.component.sjms.SjmsConsumer.java

@Override
protected void doStart() throws Exception {
    super.doStart();
    this.executor = getEndpoint().getCamelContext().getExecutorServiceManager().newDefaultThreadPool(this,
            "SjmsConsumer");
    if (consumers == null) {
        consumers = new GenericObjectPool<MessageConsumerResources>(new MessageConsumerResourcesFactory());
        consumers.setMaxActive(getConsumerCount());
        consumers.setMaxIdle(getConsumerCount());
        if (getEndpoint().isAsyncStartListener()) {
            asyncStart = getEndpoint().getComponent().getAsyncStartStopExecutorService().submit(new Runnable() {
                @Override//w w w .  j a  v a 2  s . c o m
                public void run() {
                    try {
                        fillConsumersPool();
                    } catch (Throwable e) {
                        log.warn("Error starting listener container on destination: " + getDestinationName()
                                + ". This exception will be ignored.", e);
                    }
                }

                @Override
                public String toString() {
                    return "AsyncStartListenerTask[" + getDestinationName() + "]";
                }
            });
        } else {
            fillConsumersPool();
        }
    }
}