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

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

Introduction

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

Prototype

byte WHEN_EXHAUSTED_BLOCK

To view the source code for org.apache.commons.pool.impl GenericObjectPool WHEN_EXHAUSTED_BLOCK.

Click Source Link

Document

A "when exhausted action" type indicating that when the pool is exhausted (i.e., the maximum number of active objects has been reached), the #borrowObject method should block until a new object is available, or the #getMaxWait maximum wait time has been reached.

Usage

From source file:org.dspace.storage.rdbms.DataSourceInit.java

public static DataSource getDatasource() throws SQLException {
    if (dataSource != null) {
        return dataSource;
    }/*from w  w w.j a v  a 2  s  .  c  om*/

    try {
        // Register basic JDBC driver
        Class driverClass = Class.forName(ConfigurationManager.getProperty("db.driver"));
        Driver basicDriver = (Driver) driverClass.newInstance();
        DriverManager.registerDriver(basicDriver);

        // Read pool configuration parameter or use defaults
        // Note we check to see if property is null; getIntProperty returns
        // '0' if the property is not set OR if it is actually set to zero.
        // But 0 is a valid option...
        int maxConnections = ConfigurationManager.getIntProperty("db.maxconnections");

        if (ConfigurationManager.getProperty("db.maxconnections") == null) {
            maxConnections = 30;
        }

        int maxWait = ConfigurationManager.getIntProperty("db.maxwait");

        if (ConfigurationManager.getProperty("db.maxwait") == null) {
            maxWait = 5000;
        }

        int maxIdle = ConfigurationManager.getIntProperty("db.maxidle");

        if (ConfigurationManager.getProperty("db.maxidle") == null) {
            maxIdle = -1;
        }

        boolean useStatementPool = ConfigurationManager.getBooleanProperty("db.statementpool", true);

        // Create object pool
        ObjectPool connectionPool = new GenericObjectPool(null, // PoolableObjectFactory
                // - set below
                maxConnections, // max connections
                GenericObjectPool.WHEN_EXHAUSTED_BLOCK, maxWait, // don't
                // block
                // more than 5
                // seconds
                maxIdle, // max idle connections (unlimited)
                true, // validate when we borrow connections from pool
                false // don't bother validation returned connections
        );

        // ConnectionFactory the pool will use to create connections.
        ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(
                ConfigurationManager.getProperty("db.url"), ConfigurationManager.getProperty("db.username"),
                ConfigurationManager.getProperty("db.password"));

        //
        // Now we'll create the PoolableConnectionFactory, which wraps
        // the "real" Connections created by the ConnectionFactory with
        // the classes that implement the pooling functionality.
        //
        String validationQuery = "SELECT 1";

        // Oracle has a slightly different validation query
        if ("oracle".equals(ConfigurationManager.getProperty("db.name"))) {
            validationQuery = "SELECT 1 FROM DUAL";
        }

        GenericKeyedObjectPoolFactory statementFactory = null;
        if (useStatementPool) {
            // The statement Pool is used to pool prepared statements.
            GenericKeyedObjectPool.Config statementFactoryConfig = new GenericKeyedObjectPool.Config();
            // Just grow the pool size when needed.
            //
            // This means we will never block when attempting to
            // create a query. The problem is unclosed statements,
            // they can never be reused. So if we place a maximum
            // cap on them, then we might reach a condition where
            // a page can only be viewed X number of times. The
            // downside of GROW_WHEN_EXHAUSTED is that this may
            // allow a memory leak to exist. Both options are bad,
            // but I'd prefer a memory leak over a failure.
            //
            // FIXME: Perhaps this decision should be derived from config parameters?
            statementFactoryConfig.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_GROW;

            statementFactory = new GenericKeyedObjectPoolFactory(null, statementFactoryConfig);
        }

        PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,
                connectionPool, statementFactory, validationQuery, // validation query
                false, // read only is not default for now
                false); // Autocommit defaults to none

        //
        // Finally, we create the PoolingDataSource itself...
        //
        PoolingDataSource poolingDataSource = new PoolingDataSource();

        //
        // ...and register our pool with it.
        //
        poolingDataSource.setPool(connectionPool);

        dataSource = poolingDataSource;
        return poolingDataSource;
    } catch (Exception e) {
        // Need to be able to catch other exceptions. Pretend they are
        // SQLExceptions, but do log
        log.warn("Exception initializing DB pool", e);
        throw new SQLException(e.toString(), e);
    }
}

From source file:org.dspace.storage.rdbms.MockDatabaseManager.java

/**
 * Initialize the DatabaseManager.//from   w  w w . ja  va  2 s.com
 */
@Mock
private static synchronized void initialize() throws SQLException {
    if (initialized) {
        return;
    }

    try {
        // Register basic JDBC driver
        Class.forName(ConfigurationManager.getProperty("db.driver"));

        // Register the DBCP driver
        Class.forName("org.apache.commons.dbcp.PoolingDriver");

        // Read pool configuration parameter or use defaults
        // Note we check to see if property is null; getIntProperty returns
        // '0' if the property is not set OR if it is actually set to zero.
        // But 0 is a valid option...
        int maxConnections = ConfigurationManager.getIntProperty("db.maxconnections");

        if (ConfigurationManager.getProperty("db.maxconnections") == null) {
            maxConnections = 30;
        }

        int maxWait = ConfigurationManager.getIntProperty("db.maxwait");

        if (ConfigurationManager.getProperty("db.maxwait") == null) {
            maxWait = 5000;
        }

        int maxIdle = ConfigurationManager.getIntProperty("db.maxidle");

        if (ConfigurationManager.getProperty("db.maxidle") == null) {
            maxIdle = -1;
        }

        boolean useStatementPool = ConfigurationManager.getBooleanProperty("db.statementpool", true);

        // Create object pool
        connectionPool = new GenericObjectPool(null, // PoolableObjectFactory
                // - set below
                maxConnections, // max connections
                GenericObjectPool.WHEN_EXHAUSTED_BLOCK, maxWait, // don't
                // block
                // more than 5
                // seconds
                maxIdle, // max idle connections (unlimited)
                true, // validate when we borrow connections from pool
                false // don't bother validation returned connections
        );

        // ConnectionFactory the pool will use to create connections.
        ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(
                ConfigurationManager.getProperty("db.url"), ConfigurationManager.getProperty("db.username"),
                ConfigurationManager.getProperty("db.password"));

        //
        // Now we'll create the PoolableConnectionFactory, which wraps
        // the "real" Connections created by the ConnectionFactory with
        // the classes that implement the pooling functionality.
        //
        String validationQuery = "SELECT 1";

        // Oracle has a slightly different validation query
        if ("oracle".equals(ConfigurationManager.getProperty("db.name"))) {
            validationQuery = "SELECT 1 FROM DUAL";
        }

        GenericKeyedObjectPoolFactory statementFactory = null;
        if (useStatementPool) {
            // The statement Pool is used to pool prepared statements.
            GenericKeyedObjectPool.Config statementFactoryConfig = new GenericKeyedObjectPool.Config();
            // Just grow the pool size when needed.
            //
            // This means we will never block when attempting to
            // create a query. The problem is unclosed statements,
            // they can never be reused. So if we place a maximum
            // cap on them, then we might reach a condition where
            // a page can only be viewed X number of times. The
            // downside of GROW_WHEN_EXHAUSTED is that this may
            // allow a memory leak to exist. Both options are bad,
            // but I'd prefer a memory leak over a failure.
            //
            // Perhaps this decision should be derived from config parameters?
            statementFactoryConfig.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_GROW;

            statementFactory = new GenericKeyedObjectPoolFactory(null, statementFactoryConfig);
        }

        PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,
                connectionPool, statementFactory, validationQuery, // validation query
                false, // read only is not default for now
                false); // Autocommit defaults to none

        // Obtain a poolName from the config, default is "dspacepool"
        if (ConfigurationManager.getProperty("db.poolname") != null) {
            poolName = ConfigurationManager.getProperty("db.poolname");
        }

        //
        // Finally, we get the PoolingDriver itself...
        //
        PoolingDriver driver = (PoolingDriver) DriverManager.getDriver("jdbc:apache:commons:dbcp:");

        //
        // ...and register our pool with it.
        //
        if (driver != null)
            driver.registerPool(poolName, connectionPool);

        //preload the contents of the database
        String s = new String();
        StringBuilder sb = new StringBuilder();

        String schemaPath = System.getProperty("db.schema.path");
        if (null == schemaPath)
            throw new IllegalArgumentException("System property db.schema.path must be defined");

        FileReader fr = new FileReader(new File(schemaPath));
        BufferedReader br = new BufferedReader(fr);

        while ((s = br.readLine()) != null) {
            //we skip white lines and comments
            if (!"".equals(s.trim()) && !s.trim().startsWith("--")) {
                sb.append(s);
            }
        }
        br.close();

        //we use ";" as a delimiter for each request. This assumes no triggers
        //nor other calls besides CREATE TABLE, CREATE SEQUENCE and INSERT
        //exist in the file
        String[] stmts = sb.toString().split(";");

        //stablish the connection using the pool
        Connection con = DriverManager.getConnection("jdbc:apache:commons:dbcp:" + poolName);
        Statement st = con.createStatement();

        for (int i = 0; i < stmts.length; i++) {
            // we ensure that there is no spaces before or after the request string
            // in order to not execute empty statements
            if (!stmts[i].trim().equals("")) {
                st.executeUpdate(stmts[i]);
                log.debug("Loading into database: " + stmts[i]);
            }
        }

        //commit changes
        con.commit();
        con.close();

        // Old SimplePool init
        //DriverManager.registerDriver(new SimplePool());
        initialized = true;
    } catch (SQLException se) {
        // Simply throw up SQLExceptions
        throw se;
    } catch (Exception e) {
        // Need to be able to catch other exceptions. Pretend they are
        // SQLExceptions, but do log
        log.warn("Exception initializing DB pool", e);
        throw new SQLException(e.toString());
    }
}

From source file:org.geotools.arcsde.session.SessionPool.java

/**
 * Creates a new SessionPool object for the given config.
 * //from   w  ww  . jav  a2  s.c o m
 * @param config
 *            holds connection options such as server, user and password, as well as tuning
 *            options as maximum number of connections allowed
 * @throws IOException
 *             If connection could not be established
 * @throws NullPointerException
 *             If config is null
 */
protected SessionPool(ArcSDEConnectionConfig config) throws IOException {
    if (config == null) {
        throw new NullPointerException("parameter config can't be null");
    }

    this.config = config;
    LOGGER.fine("populating ArcSDE connection pool");

    this.seConnectionFactory = createConnectionFactory();

    final int minConnections = config.getMinConnections().intValue();
    final int maxConnections = config.getMaxConnections().intValue();
    if (minConnections > maxConnections) {
        throw new IllegalArgumentException("pool.minConnections > pool.maxConnections");
    }
    {// configure connection pool

        Config poolCfg = new Config();
        // pool upper limit
        poolCfg.maxActive = config.getMaxConnections().intValue();

        // minimum number of idle objects. MAKE SURE this is 0, otherwise the pool will start
        // trying to create connections permanently even if there's a connection failure,
        // ultimately leading to the exhaustion of resources
        poolCfg.minIdle = 0;

        // how many connections may be idle at any time? -1 = no limit. We're running an
        // eviction thread to take care of idle connections (see minEvictableIdleTimeMillis and
        // timeBetweenEvictionRunsMillis)
        poolCfg.maxIdle = -1;

        // When reached the pool upper limit, block and wait for an idle connection for maxWait
        // milliseconds before failing
        poolCfg.maxWait = config.getConnTimeOut().longValue();
        if (poolCfg.maxWait > 0) {
            poolCfg.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_BLOCK;
        } else {
            poolCfg.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_FAIL;
        }

        // check connection health at borrowObject()?
        poolCfg.testOnBorrow = true;
        // check connection health at returnObject()?
        poolCfg.testOnReturn = false;
        // check periodically the health of idle connections and discard them if can't be
        // validated?
        poolCfg.testWhileIdle = false;

        // check health of idle connections every 30 seconds
        // /poolCfg.timeBetweenEvictionRunsMillis = 30000;

        // drop connections that have been idle for at least 5 minutes
        poolCfg.minEvictableIdleTimeMillis = 5 * 60 * 1000;

        pool = new GenericObjectPool(seConnectionFactory, poolCfg);

        LOGGER.fine("Created ArcSDE connection pool for " + config);
    }

    ISession[] preload = new ISession[minConnections];

    try {
        for (int i = 0; i < minConnections; i++) {
            preload[i] = (ISession) pool.borrowObject();
            if (i == 0) {
                SeRelease seRelease = preload[i].getRelease();
                String sdeDesc = seRelease.getDesc();
                int major = seRelease.getMajor();
                int minor = seRelease.getMinor();
                int bugFix = seRelease.getBugFix();
                String desc = "ArcSDE " + major + "." + minor + "." + bugFix + " " + sdeDesc;
                LOGGER.fine("Connected to " + desc);
            }
        }

        for (int i = 0; i < minConnections; i++) {
            pool.returnObject(preload[i]);
        }
    } catch (Exception e) {
        close();
        if (e instanceof IOException) {
            throw (IOException) e;
        }
        throw (IOException) new IOException().initCause(e);
    }
}

From source file:org.geotools.process.idl.impl.IDLFeatureExtractionProcessFactory.java

public IDLFeatureExtractionProcessFactory() {
    final IDLFeatureExtractionWrapperPool pool = new IDLFeatureExtractionWrapperPool(this);
    pool.setMaxActive(2);//ww w  .j  ava 2 s . c  om
    pool.setMaxIdle(2);
    pool.setMaxWait(3000000);
    pool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_BLOCK);
    setWrapperPool(pool);
}

From source file:org.geotools.referencing.factory.AbstractAuthorityMediator.java

/**
 * Constructs an instance making use of the default cache.
 *
 * @param factory The factory to cache. Can not be {@code null}.
 *//*ww  w . ja  va2  s  .  co m*/
protected AbstractAuthorityMediator(int priority, Hints hints) {
    this(priority, ObjectCaches.create(hints), ReferencingFactoryContainer.instance(hints));
    // configurable behaviour
    poolConfig.minIdle = Hints.AUTHORITY_MIN_IDLE.toValue(hints);
    poolConfig.maxIdle = Hints.AUTHORITY_MAX_IDLE.toValue(hints);
    poolConfig.maxActive = Hints.AUTHORITY_MAX_ACTIVE.toValue(hints);
    poolConfig.minEvictableIdleTimeMillis = Hints.AUTHORITY_MIN_EVICT_IDLETIME.toValue(hints);
    poolConfig.softMinEvictableIdleTimeMillis = Hints.AUTHORITY_SOFTMIN_EVICT_IDLETIME.toValue(hints);
    poolConfig.timeBetweenEvictionRunsMillis = Hints.AUTHORITY_TIME_BETWEEN_EVICTION_RUNS.toValue(hints);

    // static behaviour
    poolConfig.maxWait = -1; // block indefinitely until a worker is available
    poolConfig.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_BLOCK;
}

From source file:org.jamwiki.servlets.AdminServlet.java

/**
  */*  w  w  w  .ja v  a2s .  co  m*/
  */
private void viewAdmin(HttpServletRequest request, ModelAndView next, WikiPageInfo pageInfo, Properties props)
        throws Exception {
    pageInfo.setContentJsp(JSP_ADMIN);
    pageInfo.setAdmin(true);
    pageInfo.setPageTitle(new WikiMessage("admin.title"));
    Map editors = WikiConfiguration.getInstance().getEditors();
    next.addObject("editors", editors);
    List<WikiConfigurationObject> dataHandlers = WikiConfiguration.getInstance().getDataHandlers();
    next.addObject("dataHandlers", dataHandlers);
    List<WikiConfigurationObject> searchEngines = WikiConfiguration.getInstance().getSearchEngines();
    next.addObject("searchEngines", searchEngines);
    List<WikiConfigurationObject> parsers = WikiConfiguration.getInstance().getParsers();
    next.addObject("parsers", parsers);
    LinkedHashMap<Integer, String> poolExhaustedMap = new LinkedHashMap<Integer, String>();
    poolExhaustedMap.put(Integer.valueOf(GenericObjectPool.WHEN_EXHAUSTED_FAIL),
            "admin.persistence.caption.whenexhaustedaction.fail");
    poolExhaustedMap.put(Integer.valueOf(GenericObjectPool.WHEN_EXHAUSTED_BLOCK),
            "admin.persistence.caption.whenexhaustedaction.block");
    poolExhaustedMap.put(Integer.valueOf(GenericObjectPool.WHEN_EXHAUSTED_GROW),
            "admin.persistence.caption.whenexhaustedaction.grow");
    next.addObject("poolExhaustedMap", poolExhaustedMap);
    LinkedHashMap<Integer, String> blacklistTypesMap = new LinkedHashMap<Integer, String>();
    blacklistTypesMap.put(Integer.valueOf(WikiBase.UPLOAD_ALL), "admin.upload.caption.allowall");
    blacklistTypesMap.put(Integer.valueOf(WikiBase.UPLOAD_NONE), "admin.upload.caption.allownone");
    blacklistTypesMap.put(Integer.valueOf(WikiBase.UPLOAD_BLACKLIST), "admin.upload.caption.useblacklist");
    blacklistTypesMap.put(Integer.valueOf(WikiBase.UPLOAD_WHITELIST), "admin.upload.caption.usewhitelist");
    next.addObject("blacklistTypes", blacklistTypesMap);
    if (props == null) {
        props = Environment.getInstance();
    }
    int maximumFileSize = Integer.valueOf(props.getProperty(Environment.PROP_FILE_MAX_FILE_SIZE)) / 1000;
    next.addObject("maximumFileSize", maximumFileSize);
    next.addObject("props", props);
}

From source file:org.mule.transport.ftp.FtpConnector.java

protected GenericObjectPool createPool(FtpConnectionFactory connectionFactory) {
    GenericObjectPool genericPool = new GenericObjectPool(connectionFactory);
    byte poolExhaustedAction = ThreadingProfile.DEFAULT_POOL_EXHAUST_ACTION;

    ThreadingProfile receiverThreadingProfile = this.getReceiverThreadingProfile();
    if (receiverThreadingProfile != null) {
        int threadingProfilePoolExhaustedAction = receiverThreadingProfile.getPoolExhaustedAction();
        if (threadingProfilePoolExhaustedAction == ThreadingProfile.WHEN_EXHAUSTED_WAIT) {
            poolExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_BLOCK;
        } else if (threadingProfilePoolExhaustedAction == ThreadingProfile.WHEN_EXHAUSTED_ABORT) {
            poolExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_FAIL;
        } else if (threadingProfilePoolExhaustedAction == ThreadingProfile.WHEN_EXHAUSTED_RUN) {
            poolExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_GROW;
        }/* w  ww  .  j av  a2s  .com*/
    }

    genericPool.setWhenExhaustedAction(poolExhaustedAction);
    genericPool.setTestOnBorrow(isValidateConnections());
    return genericPool;
}

From source file:org.mule.transport.ftps.FtpsConnector.java

protected GenericObjectPool createPool(FtpsConnectionFactory connectionFactory) {
    GenericObjectPool genericPool = new GenericObjectPool(connectionFactory);
    byte poolExhaustedAction = ThreadingProfile.DEFAULT_POOL_EXHAUST_ACTION;

    ThreadingProfile receiverThreadingProfile = this.getReceiverThreadingProfile();
    if (receiverThreadingProfile != null) {
        int threadingProfilePoolExhaustedAction = receiverThreadingProfile.getPoolExhaustedAction();
        if (threadingProfilePoolExhaustedAction == ThreadingProfile.WHEN_EXHAUSTED_WAIT) {
            poolExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_BLOCK;
        } else if (threadingProfilePoolExhaustedAction == ThreadingProfile.WHEN_EXHAUSTED_ABORT) {
            poolExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_FAIL;
        } else if (threadingProfilePoolExhaustedAction == ThreadingProfile.WHEN_EXHAUSTED_RUN) {
            poolExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_GROW;
        }/*from ww  w .  ja  v a  2s  .  c  om*/
    }

    genericPool.setWhenExhaustedAction(poolExhaustedAction);
    genericPool.setTestOnBorrow(isValidateConnections());
    return genericPool;
}

From source file:org.onexus.collection.store.mysql.internal.MysqlCollectionStore.java

protected DataSource newDataSource() {

    try {/*from w  w w  .j a v a  2 s.  c  o  m*/
        Class.forName(Driver.class.getName());
    } catch (Exception e) {
        LOGGER.error("Exception: " + e.getMessage());
    }

    // Config parameters
    int maxActive = 8;
    try {
        maxActive = Integer.valueOf(getPoolMaxActive().trim()).intValue();
    } catch (Exception e) {
        LOGGER.error("Malformed config parameter 'poolMaxActive'");
    }

    byte whenExhausted = GenericObjectPool.WHEN_EXHAUSTED_BLOCK;
    try {
        if (getPoolWhenExhausted().trim().equalsIgnoreCase("FAIL")) {
            whenExhausted = GenericObjectPool.WHEN_EXHAUSTED_FAIL;
        }
        if (getPoolWhenExhausted().trim().equalsIgnoreCase("GROW")) {
            whenExhausted = GenericObjectPool.WHEN_EXHAUSTED_GROW;
        }
    } catch (Exception e) {
        LOGGER.error("Malformed config parameter 'poolWhenExhausted'");
    }

    long maxWait = GenericObjectPool.DEFAULT_MAX_WAIT;
    try {
        maxWait = Long.valueOf(getPoolMaxWait().trim()).longValue();
    } catch (Exception e) {
        LOGGER.error("Malformed config parameter 'poolMaxWait'");
    }

    // Initialize the DataSource with a connection pool
    ConnectionFactory connectionFactory = new MysqlConnectionFactory();
    GenericObjectPool connectionPool = new GenericObjectPool(null, maxActive, whenExhausted, maxWait);
    connectionPool.setTestWhileIdle(true);
    connectionPool.setTimeBetweenEvictionRunsMillis(3600);
    connectionPool.setMinEvictableIdleTimeMillis(3600);

    @SuppressWarnings("unused")
    PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,
            connectionPool, null, null, false, true);
    poolableConnectionFactory.setValidationQuery("SELECT 1");
    return new PoolingDataSource(connectionPool);

}

From source file:org.openanzo.combus.endpoint.BaseServiceListener.java

public void start() throws AnzoException {
    lock.lock();//w ww.  ja  v a 2s .  co m
    try {
        if (maxThreadPoolSize > 1) {
            threadPool = new GenericObjectPool(new ThreadPoolFactory(), maxThreadPoolSize,
                    GenericObjectPool.WHEN_EXHAUSTED_BLOCK, 0);
            threadPool.setMinIdle(minThreadPoolSize);
            threadPool.setMaxIdle(minThreadPoolSize);
            threadPool.setMinEvictableIdleTimeMillis(10000);
        }
        started = true;
        if (consumer != null) {
            try {
                consumer.setMessageListener(this);
                lowConsumer.setMessageListener(this);
            } catch (JMSException jmsex) {
                log.error(LogUtils.COMBUS_MARKER, "Error setting up consumers", jmsex);
                throw new AnzoException(ExceptionConstants.COMBUS.JMS_SERVICE_EXCEPTION, jmsex);
            }
        }
    } finally {
        lock.unlock();
    }
}