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

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

Introduction

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

Prototype

byte WHEN_EXHAUSTED_FAIL

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

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 fail, throwing a NoSuchElementException .

Usage

From source file:org.apache.camel.component.netty.NettyProducer.java

@Override
protected void doStart() throws Exception {
    super.doStart();

    if (configuration.isProducerPoolEnabled()) {
        // setup pool where we want an unbounded pool, which allows the pool to shrink on no demand
        GenericObjectPool.Config config = new GenericObjectPool.Config();
        config.maxActive = configuration.getProducerPoolMaxActive();
        config.minIdle = configuration.getProducerPoolMinIdle();
        config.maxIdle = configuration.getProducerPoolMaxIdle();
        // we should test on borrow to ensure the channel is still valid
        config.testOnBorrow = true;/*  w  w  w.java 2s  .  c  o m*/
        // only evict channels which are no longer valid
        config.testWhileIdle = true;
        // run eviction every 30th second
        config.timeBetweenEvictionRunsMillis = 30 * 1000L;
        config.minEvictableIdleTimeMillis = configuration.getProducerPoolMinEvictableIdle();
        config.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_FAIL;
        pool = new GenericObjectPool<Channel>(new NettyProducerPoolableObjectFactory(), config);

        if (LOG.isDebugEnabled()) {
            LOG.debug(
                    "Created NettyProducer pool[maxActive={}, minIdle={}, maxIdle={}, minEvictableIdleTimeMillis={}] -> {}",
                    new Object[] { config.maxActive, config.minIdle, config.maxIdle,
                            config.minEvictableIdleTimeMillis, pool });
        }
    } else {
        pool = new SharedSingletonObjectPool<Channel>(new NettyProducerPoolableObjectFactory());
        if (LOG.isDebugEnabled()) {
            LOG.info("Created NettyProducer shared singleton pool -> {}", pool);
        }
    }

    // setup pipeline factory
    ClientPipelineFactory factory = configuration.getClientPipelineFactory();
    if (factory != null) {
        pipelineFactory = factory.createPipelineFactory(this);
    } else {
        pipelineFactory = new DefaultClientPipelineFactory(this);
    }

    if (isTcp()) {
        setupTCPCommunication();
    } else {
        setupUDPCommunication();
    }

    if (!configuration.isLazyChannelCreation()) {
        // ensure the connection can be established when we start up
        Channel channel = pool.borrowObject();
        pool.returnObject(channel);
    }
}

From source file:org.apache.camel.component.netty4.NettyProducer.java

@Override
protected void doStart() throws Exception {
    super.doStart();

    if (configuration.isProducerPoolEnabled()) {
        // setup pool where we want an unbounded pool, which allows the pool to shrink on no demand
        GenericObjectPool.Config config = new GenericObjectPool.Config();
        config.maxActive = configuration.getProducerPoolMaxActive();
        config.minIdle = configuration.getProducerPoolMinIdle();
        config.maxIdle = configuration.getProducerPoolMaxIdle();
        // we should test on borrow to ensure the channel is still valid
        config.testOnBorrow = true;/*from   ww w.j a v  a2s  .  c  om*/
        // only evict channels which are no longer valid
        config.testWhileIdle = true;
        // run eviction every 30th second
        config.timeBetweenEvictionRunsMillis = 30 * 1000L;
        config.minEvictableIdleTimeMillis = configuration.getProducerPoolMinEvictableIdle();
        config.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_FAIL;
        pool = new GenericObjectPool<Channel>(new NettyProducerPoolableObjectFactory(), config);

        if (LOG.isDebugEnabled()) {
            LOG.debug(
                    "Created NettyProducer pool[maxActive={}, minIdle={}, maxIdle={}, minEvictableIdleTimeMillis={}] -> {}",
                    new Object[] { config.maxActive, config.minIdle, config.maxIdle,
                            config.minEvictableIdleTimeMillis, pool });
        }
    } else {
        pool = new SharedSingletonObjectPool<Channel>(new NettyProducerPoolableObjectFactory());
        if (LOG.isDebugEnabled()) {
            LOG.info("Created NettyProducer shared singleton pool -> {}", pool);
        }
    }

    timer = new HashedWheelTimer();

    // setup pipeline factory
    ClientPipelineFactory factory = configuration.getClientPipelineFactory();
    if (factory != null) {
        pipelineFactory = factory.createPipelineFactory(this);
    } else {
        pipelineFactory = new DefaultClientPipelineFactory(this);
    }

    if (!configuration.isLazyChannelCreation()) {
        // ensure the connection can be established when we start up
        Channel channel = pool.borrowObject();
        pool.returnObject(channel);
    }
}

From source file:org.fusesource.jms.pool.PooledConnectionFactory.java

/**
 * Creates an ObjectPoolFactory. Its behavior is controlled by the two
 * properties @see #maximumActive and @see #blockIfSessionPoolIsFull.
 *
 * @return the newly created but empty ObjectPoolFactory
 *//*w  ww .j  a v  a 2 s . co  m*/
protected ObjectPoolFactory createPoolFactory() {
    if (blockIfSessionPoolIsFull) {
        return new GenericObjectPoolFactory(null, maximumActive);
    } else {
        return new GenericObjectPoolFactory(null, maximumActive, GenericObjectPool.WHEN_EXHAUSTED_FAIL,
                GenericObjectPool.DEFAULT_MAX_WAIT);
    }
}

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

/**
 * Creates a new SessionPool object for the given config.
 * //from w  ww.  j ava  2  s .c om
 * @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.jamwiki.servlets.AdminServlet.java

/**
  */*from   ww w .  j av  a  2s .c  om*/
  */
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.jvoicexml.implementation.pool.KeyedResourcePool.java

/**
 * Adds the given resource factory./* ww  w  .  jav  a2s.co  m*/
 * @param resourceFactory The {@link ResourceFactory} to add.
 * @exception Exception error populating the pool
 */
public void addResourceFactory(final ResourceFactory<T> resourceFactory) throws Exception {
    final PoolableObjectFactory factory = new PoolableResourceFactory<T>(resourceFactory);
    final GenericObjectPool pool = new GenericObjectPool(factory);
    final int instances = resourceFactory.getInstances();
    pool.setMinIdle(instances);
    pool.setMaxActive(instances);
    pool.setMaxIdle(instances);
    pool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_FAIL);
    final String type = resourceFactory.getType();
    pools.put(type, pool);
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("loading resources of type '" + type + "'...");
    }
    for (int i = 0; i < instances; i++) {
        pool.addObject();
    }
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("...resources loaded.");
    }
}

From source file:org.kiji.schema.impl.hbase.KijiHTablePool.java

/**
 * Primary constructor./*from w w  w  . j av  a  2 s. c  om*/
 *
 * @param name The name of the table that will be used with this pool.
 * @param kiji The HBaseKiji instance backing these tables.
 * @param tableFactory A factory to create the underlying HTableInterfaces.  This factory must
 *     create HTables.
 */
public KijiHTablePool(String name, HBaseKiji kiji, HTableInterfaceFactory tableFactory) {
    mTableName = name;
    mHTableFactory = tableFactory;
    mKiji = kiji;

    mConstructorStack = CLEANUP_LOG.isDebugEnabled() ? Debug.getStackTrace() : null;

    mHBaseTableName = KijiManagedHBaseTableName.getKijiTableName(mKiji.getURI().getInstance(), mTableName)
            .toString();

    final GenericObjectPool.Config config = new GenericObjectPool.Config();

    config.maxActive = -1;
    config.maxIdle = -1;
    // This state should not occur, so throw an exception.
    config.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_FAIL;
    config.testOnBorrow = true;

    mPool = new GenericObjectPool<PooledHTable>(new PooledHTableFactory(), config);
}

From source file:org.mobicents.servlet.sip.example.SimpleSipServlet.java

@Override
public void init(ServletConfig servletConfig) throws ServletException {
    logger.info("the simple sip servlet has been started");
    super.init(servletConfig);

    RABBITMQ_CONN_URL = servletConfig.getInitParameter("rabbitmq_conn_url");
    EXCHANGE_NAME = servletConfig.getInitParameter("exchange_name");
    String pool_max_active = servletConfig.getInitParameter("rabbitmq_pool_max_active");
    String pool_max_idle = servletConfig.getInitParameter("rabbitmq_pool_max_idle");
    String pool_min_idle = servletConfig.getInitParameter("rabbitmq_pool_min_idle");
    String time_between_evication = servletConfig.getInitParameter("rabbitmq_pool_time_between_eviction");
    String idle_time_before_eviction = servletConfig
            .getInitParameter("rabbitmq_pool_idle_time_before_eviction");

    logger.info("INIT PARAM:  rabbitmq_conn_url = " + RABBITMQ_CONN_URL);
    logger.info("INIT PARAM : exchange name  = " + EXCHANGE_NAME);
    logger.info("INIT PARAM : pool max active = " + pool_max_active);
    logger.info("INIT PARAM : pool max idle  = " + pool_max_idle);
    logger.info("INIT PARAM : pool min idle = " + pool_min_idle);
    logger.info("INIT PARAM : time_between_evication  = " + time_between_evication);
    logger.info("INIT PARAM : idle_time_before_eviction  = " + idle_time_before_eviction);

    try {/*  w w w .j  a va2 s.  co  m*/
        POOL_MAX_ACTIVE = Integer.parseInt(pool_max_active);
    } catch (NumberFormatException e) {
        logger.error("Impossible to parse the pool max active : " + pool_max_active, e);
    }

    try {
        POOL_MAX_IDLE = Integer.parseInt(pool_max_idle);
    } catch (NumberFormatException e) {
        logger.error("Impossible to parse the pool max idle : " + pool_max_idle, e);
    }

    try {
        POOL_MIN_IDLE = Integer.parseInt(pool_min_idle);
    } catch (NumberFormatException e) {
        logger.error("Impossible to parse the pool min idle  : " + pool_min_idle, e);
    }

    try {
        TIME_BETWEEN_EVICTION = Integer.parseInt(time_between_evication);
    } catch (NumberFormatException e) {
        logger.error("Impossible to parse the time between eviction : " + time_between_evication, e);
    }
    try {
        IDL_TIME_BEFORE_EVICTION = Integer.parseInt(idle_time_before_eviction);
    } catch (NumberFormatException e) {
        logger.error("Impossible to parse idle time before eviction : " + idle_time_before_eviction, e);
    }

    /**
     * create static instance of rabbitmq connection pool
     */
    try {

        GenericObjectPool.Config config = new GenericObjectPool.Config();
        config.maxActive = POOL_MAX_ACTIVE;
        config.maxIdle = POOL_MAX_IDLE;
        config.minIdle = POOL_MIN_IDLE;
        config.timeBetweenEvictionRunsMillis = TIME_BETWEEN_EVICTION;
        config.minEvictableIdleTimeMillis = IDL_TIME_BEFORE_EVICTION;
        config.testOnBorrow = false;
        config.testOnReturn = false;
        config.lifo = GenericObjectPool.DEFAULT_LIFO;
        config.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_FAIL;

        pool = new GenericObjectPool<Channel>(new ConnectionPoolableObjectFactory(RABBITMQ_CONN_URL), config);

        //create an initial pool instances.
        /*
        int initSize = 25;
        for (int i =0; i < initSize; i++) {
           try {
              pool.addObject();
           } catch (Exception e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
           }
        }
        */

        /*
        pool.setMaxActive(POOL_MAX_ACTIVE);   //maximum connection allowed in the pool (100). If reached, worker thread needs to be blocked to wait.
        pool.setMinIdle(POOL_MIN_IDLE);       //keep minimum idle connection (set to 3) in pool in all time.
        pool.setMaxIdle(POOL_MAX_IDLE);      //No minimum to create new connection when needed (set to -1).
        pool.setTimeBetweenEvictionRunsMillis(TIME_BETWEEN_EVICTION);   //wait up eviction thread in 10 second
        pool.setMinEvictableIdleTimeMillis(IDL_TIME_BEFORE_EVICTION);  //kill the idle connection that is 5 second old
        pool.setTestOnBorrow(true);   //sanity checking when getting connection from pool.
        pool.setTestOnReturn(true);   //sanity check when returning connection to pool.
        */

    } catch (IOException ex) {

        logger.error("RabbitMQ Pool failed to create. Error = " + ex.getMessage());
        throw new ServletException(ex);
    }

    //logger.info("HELLO... FINISHED LOADING THE RABBITMQ CONNECTION/CHANNEL POOL");

}

From source file:org.mobicents.slee.container.profile.ProfileObjectPoolManagement.java

public ProfileObjectPoolManagement(SleeContainer sleeContainer) {
    this.sleeContainer = sleeContainer;
    // create pool config mbean with default pool configuration
    config = new GenericObjectPool.Config();
    config.maxActive = -1;//from  www  .  j av a 2s . c om
    config.maxIdle = 50;
    config.maxWait = -1;
    config.minEvictableIdleTimeMillis = 60000;
    config.minIdle = 0;
    config.numTestsPerEvictionRun = -1;
    config.testOnBorrow = true;
    config.testOnReturn = true;
    config.testWhileIdle = false;
    config.timeBetweenEvictionRunsMillis = 300000;
    config.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_FAIL;
    // create pools map
    pools = new ConcurrentHashMap<String, ProfileObjectPool>();
}

From source file:org.mobicents.slee.runtime.sbb.SbbObjectPoolManagementImpl.java

public SbbObjectPoolManagementImpl(SleeContainer sleeContainer) {
    this.sleeContainer = sleeContainer;
    // create pool config mbean with default pool configuration
    config = new GenericObjectPool.Config();
    config.maxActive = -1;/*from   w ww .j a  v a 2 s  . c  o m*/
    config.maxIdle = 50;
    config.maxWait = -1;
    config.minEvictableIdleTimeMillis = 60000;
    config.minIdle = 0;
    config.numTestsPerEvictionRun = -1;
    config.testOnBorrow = true;
    config.testOnReturn = true;
    config.testWhileIdle = false;
    config.timeBetweenEvictionRunsMillis = 300000;
    config.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_FAIL;
    // create pools map
    pools = new ConcurrentHashMap<ObjectPoolMapKey, SbbObjectPoolImpl>();
}