Example usage for org.apache.commons.pool2.impl GenericObjectPoolConfig setJmxEnabled

List of usage examples for org.apache.commons.pool2.impl GenericObjectPoolConfig setJmxEnabled

Introduction

In this page you can find the example usage for org.apache.commons.pool2.impl GenericObjectPoolConfig setJmxEnabled.

Prototype

public void setJmxEnabled(boolean jmxEnabled) 

Source Link

Document

Sets the value of the flag that determines if JMX will be enabled for pools created with this configuration instance.

Usage

From source file:com.reversemind.hypergate.client.ClientPool.java

private static GenericObjectPoolConfig createConfig(int poolSize) {
    GenericObjectPoolConfig genericObjectPoolConfig = new GenericObjectPoolConfig();
    genericObjectPoolConfig.setJmxEnabled(true);
    genericObjectPoolConfig.setJmxNameBase("HyperGatePool");
    genericObjectPoolConfig.setJmxNamePrefix("HyperGatePoolPrefix");
    genericObjectPoolConfig.setBlockWhenExhausted(false);
    genericObjectPoolConfig.setMinIdle(0);
    genericObjectPoolConfig.setTestOnBorrow(true);
    genericObjectPoolConfig.setMaxWaitMillis(500);
    START_POOL_SIZE = poolSize;/*from  w  w w  .ja v  a  2s.  c om*/
    genericObjectPoolConfig.setMaxTotal(START_POOL_SIZE);
    genericObjectPoolConfig.setMaxIdle(START_POOL_SIZE);
    return genericObjectPoolConfig;
}

From source file:com.baidu.jprotobuf.pbrpc.transport.ChannelPool.java

/**
 * Instantiates a new channel pool./*from  w w w .j  a  va2s . c o  m*/
 *
 * @param rpcClient the rpc client
 * @param host the host
 * @param port the port
 */
public ChannelPool(RpcClient rpcClient, String host, int port) {
    this.clientConfig = rpcClient.getRpcClientOptions();
    objectFactory = new ChannelPoolObjectFactory(rpcClient, host, port);

    GenericObjectPoolConfig config = new GenericObjectPoolConfig();
    config.setJmxEnabled(clientConfig.isJmxEnabled());
    pool = new GenericObjectPool<Connection>(objectFactory, config);
    pool.setMaxIdle(clientConfig.getMaxIdleSize());
    pool.setMaxTotal(clientConfig.getThreadPoolSize());
    pool.setMaxWaitMillis(clientConfig.getMaxWait());
    pool.setMinIdle(clientConfig.getMinIdleSize());
    pool.setMinEvictableIdleTimeMillis(clientConfig.getMinEvictableIdleTime());
    pool.setTestOnBorrow(clientConfig.isTestOnBorrow());
    pool.setTestOnReturn(clientConfig.isTestOnReturn());
    pool.setLifo(clientConfig.isLifo());
}

From source file:ch.cyberduck.core.pool.DefaultSessionPool.java

public DefaultSessionPool(final ConnectionService connect, final X509TrustManager trust,
        final X509KeyManager key, final VaultRegistry registry, final PathCache cache,
        final TranscriptListener transcript, final Host bookmark) {
    this.connect = connect;
    this.registry = registry;
    this.cache = cache;
    this.bookmark = bookmark;
    this.transcript = transcript;
    final GenericObjectPoolConfig configuration = new GenericObjectPoolConfig();
    configuration.setJmxEnabled(false);
    configuration.setEvictionPolicyClassName(CustomPoolEvictionPolicy.class.getName());
    configuration.setBlockWhenExhausted(true);
    configuration.setMaxWaitMillis(BORROW_MAX_WAIT_INTERVAL);
    this.pool = new GenericObjectPool<Session>(
            new PooledSessionFactory(connect, trust, key, cache, bookmark, registry), configuration);
    final AbandonedConfig abandon = new AbandonedConfig();
    abandon.setUseUsageTracking(true);//  ww  w  .  j  a v  a2  s  . com
    this.pool.setAbandonedConfig(abandon);
}

From source file:com.heliosapm.streams.collector.ds.AbstractDataSourceFactory.java

/**
 * Reads the generic object pool configuration from the passed JSONObject
 * @param jsonConfig The json configuration for the current data source
 * @return the pool config//from   w  w w.ja  v  a 2s  .c  o m
 */
protected GenericObjectPoolConfig getPoolConfig(final JsonNode jsonConfig) {
    if (jsonConfig == null)
        throw new IllegalArgumentException("The passed JSONObject was null");
    final GenericObjectPoolConfig config = new GenericObjectPoolConfig();
    if (jsonConfig.has("maxPoolSize"))
        config.setMaxTotal(jsonConfig.get("maxPoolSize").intValue());
    if (jsonConfig.has("maxPoolIdle"))
        config.setMaxIdle(jsonConfig.get("maxPoolIdle").intValue());
    if (jsonConfig.has("minPoolIdle"))
        config.setMinIdle(jsonConfig.get("minPoolIdle").intValue());
    if (jsonConfig.has("registerMbeans"))
        config.setJmxEnabled(jsonConfig.get("registerMbeans").booleanValue());
    if (jsonConfig.has("fair"))
        config.setFairness(jsonConfig.get("fair").booleanValue());
    if (jsonConfig.has("lifo"))
        config.setLifo(jsonConfig.get("lifo").booleanValue());
    if (jsonConfig.has("maxWait"))
        config.setMaxWaitMillis(jsonConfig.get("maxWait").longValue());

    final boolean testWhileIdle;
    if (jsonConfig.has("testWhileIdle")) {
        testWhileIdle = jsonConfig.get("testWhileIdle").booleanValue();
    } else {
        testWhileIdle = false;
    }
    if (testWhileIdle) {
        config.setTestWhileIdle(true);
        long testPeriod = 15000;
        if (jsonConfig.has("testPeriod")) {
            testPeriod = jsonConfig.get("testPeriod").longValue();
        }
        config.setTimeBetweenEvictionRunsMillis(testPeriod);
    } else {
        config.setTestWhileIdle(false);
    }
    // ALWAYS test on borrow
    config.setTestOnBorrow(true);
    config.setTestOnCreate(true);
    config.setTestOnReturn(false);
    return config;
}

From source file:ch.cyberduck.core.worker.ConcurrentTransferWorker.java

public ConcurrentTransferWorker(final ConnectionService connect, final Transfer transfer,
        final TransferOptions options, final TransferSpeedometer meter, final TransferPrompt prompt,
        final TransferErrorCallback error, final TransferItemCallback transferItemCallback,
        final ConnectionCallback connectionCallback, final ProgressListener progressListener,
        final StreamListener streamListener, final X509TrustManager trust, final X509KeyManager key,
        final PathCache cache, final Integer connections) {
    super(transfer, options, prompt, meter, error, transferItemCallback, progressListener, streamListener,
            connectionCallback);/*w  w w .  j  a v  a 2s  .c  o  m*/
    final GenericObjectPoolConfig configuration = new GenericObjectPoolConfig() {
        @Override
        public String toString() {
            final StringBuilder sb = new StringBuilder("GenericObjectPoolConfig{");
            sb.append("connections=").append(connections);
            sb.append('}');
            return sb.toString();
        }
    };
    configuration.setJmxEnabled(false);
    configuration.setMinIdle(0);
    configuration.setMaxTotal(connections);
    configuration.setMaxIdle(connections);
    configuration.setBlockWhenExhausted(true);
    configuration.setMaxWaitMillis(BORROW_MAX_WAIT_INTERVAL);
    progress = progressListener;
    retry = Integer.max(PreferencesFactory.get().getInteger("connection.retry"), connections);
    pool = new GenericObjectPool<Session>(new SessionPool(connect, trust, key, cache, transfer.getHost()),
            configuration) {
        @Override
        public String toString() {
            final StringBuilder sb = new StringBuilder("GenericObjectPool{");
            sb.append("configuration=").append(configuration);
            sb.append('}');
            return sb.toString();
        }
    };
    completion = new DefaultThreadPool<TransferStatus>(connections, "transfer");
}

From source file:JDBCPool.dbcp.demo.sourcecode.BasicDataSource.java

/**
 * Creates a connection pool for this datasource.  This method only exists
 * so subclasses can replace the implementation class.
 *
 * This implementation configures all pool properties other than
 * timeBetweenEvictionRunsMillis.  Setting that property is deferred to
 * {@link #startPoolMaintenance()}, since setting timeBetweenEvictionRunsMillis
 * to a positive value causes {@link GenericObjectPool}'s eviction timer
 * to be started.//  w w  w.  j  a va2 s  .  c om
 */
protected void createConnectionPool(PoolableConnectionFactory factory) {
    // Create an object pool to contain our active connections
    GenericObjectPoolConfig config = new GenericObjectPoolConfig();
    updateJmxName(config);
    config.setJmxEnabled(registeredJmxName != null); // Disable JMX on the underlying pool if the DS is not registered.
    GenericObjectPool<PoolableConnection> gop;
    if (abandonedConfig != null && (abandonedConfig.getRemoveAbandonedOnBorrow()
            || abandonedConfig.getRemoveAbandonedOnMaintenance())) {
        gop = new GenericObjectPool<>(factory, config, abandonedConfig);
    } else {
        gop = new GenericObjectPool<>(factory, config);
    }
    gop.setMaxTotal(maxTotal);
    gop.setMaxIdle(maxIdle);
    gop.setMinIdle(minIdle);
    gop.setMaxWaitMillis(maxWaitMillis);
    gop.setTestOnCreate(testOnCreate);
    gop.setTestOnBorrow(testOnBorrow);
    gop.setTestOnReturn(testOnReturn);
    gop.setNumTestsPerEvictionRun(numTestsPerEvictionRun);
    gop.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
    gop.setTestWhileIdle(testWhileIdle);
    gop.setLifo(lifo);
    gop.setSwallowedExceptionListener(new SwallowedExceptionLogger(log, logExpiredConnections));
    gop.setEvictionPolicyClassName(evictionPolicyClassName);
    factory.setPool(gop);
    connectionPool = gop;
}

From source file:net.ymate.platform.persistence.redis.impl.RedisModuleCfg.java

@SuppressWarnings("unchecked")
protected RedisDataSourceCfgMeta __doParserDataSourceCfgMeta(String dsName, Map<String, String> _moduleCfgs)
        throws Exception {
    RedisDataSourceCfgMeta _meta = null;
    ////from  w ww  . ja  v  a 2  s  . c o  m
    Map<String, String> _dataSourceCfgs = __doGetCfgs(_moduleCfgs, "ds." + dsName + ".");
    //
    //        if (!_dataSourceCfgs.isEmpty()) {
    String _connectionType = StringUtils.defaultIfBlank(_dataSourceCfgs.get("connection_type"), "default");
    String _masterServerName = StringUtils.defaultIfBlank(_dataSourceCfgs.get("master_server_name"), "default");
    List<ServerMeta> _servers = new ArrayList<ServerMeta>();
    String[] _serverNames = StringUtils
            .split(StringUtils.defaultIfBlank(_dataSourceCfgs.get("server_name_list"), "default"), "|");
    Map<String, String> _tmpCfgs = null;
    if (_serverNames != null) {
        for (String _serverName : _serverNames) {
            _tmpCfgs = __doGetCfgs(_dataSourceCfgs, "server." + _serverName + ".");
            if (!_tmpCfgs.isEmpty()) {
                ServerMeta _servMeta = new ServerMeta();
                _servMeta.setName(_serverName);
                _servMeta.setHost(StringUtils.defaultIfBlank(_tmpCfgs.get("host"), "localhost"));
                _servMeta.setPort(
                        BlurObject.bind(StringUtils.defaultIfBlank(_tmpCfgs.get("port"), "6379")).toIntValue());
                _servMeta.setTimeout(BlurObject
                        .bind(StringUtils.defaultIfBlank(_tmpCfgs.get("timeout"), "2000")).toIntValue());
                _servMeta.setWeight(
                        BlurObject.bind(StringUtils.defaultIfBlank(_tmpCfgs.get("weight"), "1")).toIntValue());
                _servMeta.setDatabase(BlurObject.bind(StringUtils.defaultIfBlank(_tmpCfgs.get("database"), "0"))
                        .toIntValue());
                _servMeta.setClientName(StringUtils.trimToNull(_tmpCfgs.get("client_name")));
                _servMeta.setPassword(StringUtils.trimToNull(_tmpCfgs.get("password")));
                //
                boolean _pwdEncrypted = new BlurObject(_tmpCfgs.get("password_encrypted")).toBooleanValue();
                //
                if (_pwdEncrypted && StringUtils.isNotBlank(_servMeta.getPassword())
                        && StringUtils.isNotBlank(_tmpCfgs.get("password_class"))) {
                    IPasswordProcessor _proc = ClassUtils.impl(_dataSourceCfgs.get("password_class"),
                            IPasswordProcessor.class, this.getClass());
                    if (_proc != null) {
                        _servMeta.setPassword(_proc.decrypt(_servMeta.getPassword()));
                    }
                }
                //
                _servers.add(_servMeta);
            }
        }
    }
    //
    GenericObjectPoolConfig _poolConfig = new GenericObjectPoolConfig();
    _tmpCfgs = __doGetCfgs(_dataSourceCfgs, "pool.");
    if (!_tmpCfgs.isEmpty()) {
        _poolConfig.setMinIdle(BlurObject.bind(StringUtils.defaultIfBlank(_tmpCfgs.get("min_idle"),
                GenericObjectPoolConfig.DEFAULT_MIN_IDLE + "")).toIntValue());
        _poolConfig.setMaxIdle(BlurObject.bind(StringUtils.defaultIfBlank(_tmpCfgs.get("max_idle"),
                GenericObjectPoolConfig.DEFAULT_MAX_IDLE + "")).toIntValue());
        _poolConfig.setMaxTotal(BlurObject.bind(StringUtils.defaultIfBlank(_tmpCfgs.get("max_total"),
                GenericObjectPoolConfig.DEFAULT_MAX_TOTAL + "")).toIntValue());
        _poolConfig
                .setBlockWhenExhausted(
                        BlurObject
                                .bind(StringUtils.defaultIfBlank(_tmpCfgs.get("block_when_exhausted"),
                                        GenericObjectPoolConfig.DEFAULT_BLOCK_WHEN_EXHAUSTED + ""))
                                .toBooleanValue());
        _poolConfig.setFairness(BlurObject.bind(StringUtils.defaultIfBlank(_tmpCfgs.get("fairness"),
                GenericObjectPoolConfig.DEFAULT_FAIRNESS + "")).toBooleanValue());
        _poolConfig.setJmxEnabled(BlurObject.bind(StringUtils.defaultIfBlank(_tmpCfgs.get("jmx_enabled"),
                GenericObjectPoolConfig.DEFAULT_JMX_ENABLE + "")).toBooleanValue());
        _poolConfig.setJmxNameBase(StringUtils.defaultIfBlank(_tmpCfgs.get("jmx_name_base"),
                GenericObjectPoolConfig.DEFAULT_JMX_NAME_BASE));
        _poolConfig.setJmxNamePrefix(StringUtils.defaultIfBlank(_tmpCfgs.get("jmx_name_prefix"),
                GenericObjectPoolConfig.DEFAULT_JMX_NAME_PREFIX));
        _poolConfig.setEvictionPolicyClassName(
                StringUtils.defaultIfBlank(_tmpCfgs.get("eviction_policy_class_name"),
                        GenericObjectPoolConfig.DEFAULT_EVICTION_POLICY_CLASS_NAME));
        _poolConfig.setLifo(BlurObject.bind(
                StringUtils.defaultIfBlank(_tmpCfgs.get("lifo"), GenericObjectPoolConfig.DEFAULT_LIFO + ""))
                .toBooleanValue());
        _poolConfig.setMaxWaitMillis(BlurObject.bind(StringUtils.defaultIfBlank(_tmpCfgs.get("max_wait_millis"),
                GenericObjectPoolConfig.DEFAULT_MAX_WAIT_MILLIS + "")).toLongValue());
        _poolConfig
                .setMinEvictableIdleTimeMillis(BlurObject
                        .bind(StringUtils.defaultIfBlank(_tmpCfgs.get("min_evictable_idle_time_millis"),
                                GenericObjectPoolConfig.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS + ""))
                        .toLongValue());
        _poolConfig.setSoftMinEvictableIdleTimeMillis(BlurObject
                .bind(StringUtils.defaultIfBlank(_tmpCfgs.get("soft_min_evictable_idle_time_millis"),
                        GenericObjectPoolConfig.DEFAULT_SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS + ""))
                .toLongValue());
        _poolConfig.setTestOnBorrow(BlurObject.bind(StringUtils.defaultIfBlank(_tmpCfgs.get("test_on_borrow"),
                GenericObjectPoolConfig.DEFAULT_TEST_ON_BORROW + "")).toBooleanValue());
        _poolConfig.setTestOnReturn(BlurObject.bind(StringUtils.defaultIfBlank(_tmpCfgs.get("test_on_return"),
                GenericObjectPoolConfig.DEFAULT_TEST_ON_RETURN + "")).toBooleanValue());
        _poolConfig.setTestOnCreate(BlurObject.bind(StringUtils.defaultIfBlank(_tmpCfgs.get("test_on_create"),
                GenericObjectPoolConfig.DEFAULT_TEST_ON_CREATE + "")).toBooleanValue());
        _poolConfig
                .setTestWhileIdle(
                        BlurObject
                                .bind(StringUtils.defaultIfBlank(_tmpCfgs.get("test_while_idle"),
                                        GenericObjectPoolConfig.DEFAULT_TEST_WHILE_IDLE + ""))
                                .toBooleanValue());
        _poolConfig
                .setNumTestsPerEvictionRun(
                        BlurObject
                                .bind(StringUtils.defaultIfBlank(_tmpCfgs.get("num_tests_per_eviction_run"),
                                        GenericObjectPoolConfig.DEFAULT_NUM_TESTS_PER_EVICTION_RUN + ""))
                                .toIntValue());
        _poolConfig
                .setTimeBetweenEvictionRunsMillis(BlurObject
                        .bind(StringUtils.defaultIfBlank(_tmpCfgs.get("time_between_eviction_runs_millis"),
                                GenericObjectPoolConfig.DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS + ""))
                        .toLongValue());
    }
    _meta = new RedisDataSourceCfgMeta(dsName, _connectionType, _masterServerName, _servers, _poolConfig);
    //        }
    return _meta;
}

From source file:org.cloudgraph.hbase.connect.HBaseConnectionManager.java

private HBaseConnectionManager() {
    this.config = CloudGraphContext.instance().getConfig();

    GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();

    poolConfig.setMaxTotal(/*  ww  w  . j  a  va  2s .c o  m*/
            this.config.getInt(CONNECTION_POOL_MAX_TOTAL, GenericObjectPoolConfig.DEFAULT_MAX_TOTAL));
    if (this.config.get(CONNECTION_POOL_MAX_SIZE) != null)
        poolConfig.setMaxTotal(
                this.config.getInt(CONNECTION_POOL_MAX_SIZE, GenericObjectPoolConfig.DEFAULT_MAX_TOTAL));

    poolConfig
            .setMaxIdle(this.config.getInt(CONNECTION_POOL_MAX_IDLE, GenericObjectPoolConfig.DEFAULT_MAX_IDLE));
    poolConfig
            .setMinIdle(this.config.getInt(CONNECTION_POOL_MIN_IDLE, GenericObjectPoolConfig.DEFAULT_MIN_IDLE));
    if (this.config.get(CONNECTION_POOL_MIN_SIZE) != null)
        poolConfig.setMinIdle(
                this.config.getInt(CONNECTION_POOL_MIN_SIZE, GenericObjectPoolConfig.DEFAULT_MIN_IDLE));

    poolConfig.setLifo(this.config.getBoolean(CONNECTION_POOL_LIFO, GenericObjectPoolConfig.DEFAULT_LIFO));

    poolConfig.setMaxWaitMillis(this.config.getLong(CONNECTION_POOL_MAX_WAIT_MILLIS,
            GenericObjectPoolConfig.DEFAULT_MAX_WAIT_MILLIS));

    // eviction
    poolConfig.setTimeBetweenEvictionRunsMillis(
            this.config.getLong(CONNECTION_POOL_TIME_BETWEEN_EVICTION_RUNS_MILLIS,
                    GenericObjectPoolConfig.DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS));
    poolConfig.setEvictionPolicyClassName(this.config.get(CONNECTION_POOL_EVICTION_POLICY_CLASS_NAME,
            GenericObjectPoolConfig.DEFAULT_EVICTION_POLICY_CLASS_NAME));
    poolConfig.setMinEvictableIdleTimeMillis(this.config.getLong(CONNECTION_POOL_MIN_EVICTABLE_IDLE_TIME_MILLIS,
            GenericObjectPoolConfig.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS));
    poolConfig.setSoftMinEvictableIdleTimeMillis(
            this.config.getLong(CONNECTION_POOL_SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS,
                    GenericObjectPoolConfig.DEFAULT_SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS));
    poolConfig.setNumTestsPerEvictionRun(this.config.getInt(CONNECTION_POOL_NUM_TESTS_PER_EVICTION_RUN,
            GenericObjectPoolConfig.DEFAULT_NUM_TESTS_PER_EVICTION_RUN));

    poolConfig.setTestOnCreate(this.config.getBoolean(CONNECTION_POOL_TEST_ON_CREATE,
            GenericObjectPoolConfig.DEFAULT_TEST_ON_CREATE));
    poolConfig.setTestOnBorrow(this.config.getBoolean(CONNECTION_POOL_TEST_ON_BORROW,
            GenericObjectPoolConfig.DEFAULT_TEST_ON_BORROW));
    poolConfig.setTestOnReturn(this.config.getBoolean(CONNECTION_POOL_TEST_ON_RETURN,
            GenericObjectPoolConfig.DEFAULT_TEST_ON_RETURN));
    poolConfig.setTestWhileIdle(this.config.getBoolean(CONNECTION_POOL_TEST_WHILE_IDLE,
            GenericObjectPoolConfig.DEFAULT_TEST_WHILE_IDLE));
    poolConfig.setBlockWhenExhausted(this.config.getBoolean(CONNECTION_POOL_BLOCK_WHEN_EXHAUSTED,
            GenericObjectPoolConfig.DEFAULT_BLOCK_WHEN_EXHAUSTED));
    poolConfig.setJmxEnabled(this.config.getBoolean(CONNECTION_POOL_JMX_ENABLED, false));
    poolConfig.setJmxNameBase(
            this.config.get(CONNECTION_POOL_JMX_NAME_BASE, GenericObjectPoolConfig.DEFAULT_JMX_NAME_BASE));
    poolConfig.setJmxNamePrefix(
            this.config.get(CONNECTION_POOL_JMX_NAME_PREFIX, GenericObjectPoolConfig.DEFAULT_JMX_NAME_PREFIX));

    PooledConnectionFactory factory = new PooledConnectionFactory(this.config);
    this.pool = new GenericObjectPool<Connection>(factory, poolConfig);
    factory.setPool(pool);

    log.info("created connection pool[ " + "\n\tMaxTotal:\t\t" + poolConfig.getMaxTotal() + "\n\tMinIdle:\t\t"
            + poolConfig.getMinIdle() + "\n\tMaxIdle:\t\t" + poolConfig.getMaxIdle() + "\n\tLifo:\t\t"
            + poolConfig.getLifo() + "\n\tMaxWaitMillis:\t\t" + poolConfig.getMaxWaitMillis()
            + "\n\tTimeBetweenEvictionRunsMillis:\t\t" + poolConfig.getTimeBetweenEvictionRunsMillis()
            + "\n\tEvictionPolicyClassName:\t\t" + poolConfig.getEvictionPolicyClassName()
            + "\n\tMinEvictableIdleTimeMillis:\t\t" + poolConfig.getMinEvictableIdleTimeMillis()
            + "\n\tSoftMinEvictableIdleTimeMillis:\t\t" + poolConfig.getSoftMinEvictableIdleTimeMillis()
            + "\n\tNumTestsPerEvictionRun:\t\t" + poolConfig.getNumTestsPerEvictionRun() + "\n...]");
}

From source file:org.jooby.jedis.Redis.java

private GenericObjectPoolConfig poolConfig(final Config config) {
    GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
    poolConfig.setBlockWhenExhausted(config.getBoolean("blockWhenExhausted"));
    poolConfig.setEvictionPolicyClassName(config.getString("evictionPolicyClassName"));
    poolConfig.setJmxEnabled(config.getBoolean("jmxEnabled"));
    poolConfig.setJmxNamePrefix(config.getString("jmxNamePrefix"));
    poolConfig.setLifo(config.getBoolean("lifo"));
    poolConfig.setMaxIdle(config.getInt("maxIdle"));
    poolConfig.setMaxTotal(config.getInt("maxTotal"));
    poolConfig.setMaxWaitMillis(config.getDuration("maxWait", TimeUnit.MILLISECONDS));
    poolConfig.setMinEvictableIdleTimeMillis(config.getDuration("minEvictableIdle", TimeUnit.MILLISECONDS));
    poolConfig.setMinIdle(config.getInt("minIdle"));
    poolConfig.setNumTestsPerEvictionRun(config.getInt("numTestsPerEvictionRun"));
    poolConfig.setSoftMinEvictableIdleTimeMillis(
            config.getDuration("softMinEvictableIdle", TimeUnit.MILLISECONDS));
    poolConfig.setTestOnBorrow(config.getBoolean("testOnBorrow"));
    poolConfig.setTestOnReturn(config.getBoolean("testOnReturn"));
    poolConfig.setTestWhileIdle(config.getBoolean("testWhileIdle"));
    poolConfig.setTimeBetweenEvictionRunsMillis(
            config.getDuration("timeBetweenEvictionRuns", TimeUnit.MILLISECONDS));

    return poolConfig;
}

From source file:org.nd4j.linalg.jcublas.context.ContextHolder.java

/**
 * Configure the given information//from w  w w  .  jav a2  s  .com
 * based on the device
 */
public void configure() {
    if (confCalled)
        return;

    JCublas2.setExceptionsEnabled(true);
    JCudaDriver.setExceptionsEnabled(true);
    JCuda.setExceptionsEnabled(true);

    if (deviceSetup.get())
        return;

    JCudaDriver.cuInit(0);
    int count[] = new int[1];
    cuDeviceGetCount(count);
    numDevices = count[0];
    log.debug("Found " + numDevices + " gpus");

    if (numDevices < 1)
        numDevices = 1;
    bannedDevices = new ArrayList<>();

    String props = System.getProperty(DEVICES_TO_BAN, "-1");
    String[] split = props.split(",");
    //Should only be used in multi device scenarios; otherwise always use one device
    if (split.length >= 1)
        for (String s : split) {
            Integer i = Integer.parseInt(s);
            if (i >= 0)
                bannedDevices.add(Integer.parseInt(s));

        }

    deviceSetup.set(true);
    Set<Thread> threadSet = Thread.getAllStackTraces().keySet();

    for (int i = 0; i < numDevices; i++) {
        for (Thread thread : threadSet)
            getContext(i, thread.getName());
    }

    setContext();

    try {
        KernelFunctionLoader.getInstance().load();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    // Check if the device supports mapped host memory
    cudaDeviceProp deviceProperties = new cudaDeviceProp();
    JCuda.cudaGetDeviceProperties(deviceProperties, 0);
    if (deviceProperties.canMapHostMemory == 0) {
        System.err.println("This device can not map host memory");
        System.err.println(deviceProperties.toFormattedString());
        return;
    }

    //force certain ops to have a certain number of threads
    Properties threadProps = new Properties();
    try {
        InputStream is = ContextHolder.class.getResourceAsStream("/function_threads.properties");
        threadProps.load(is);
    } catch (IOException e) {
        e.printStackTrace();
    }

    for (String prop : threadProps.stringPropertyNames()) {
        threads.put(prop, Integer.parseInt(threadProps.getProperty(prop)));
    }

    try {
        GenericObjectPoolConfig config = new GenericObjectPoolConfig();
        config.setJmxEnabled(true);
        config.setBlockWhenExhausted(false);
        config.setMaxIdle(Runtime.getRuntime().availableProcessors());
        config.setMaxTotal(Runtime.getRuntime().availableProcessors());
        config.setMinIdle(Runtime.getRuntime().availableProcessors());
        config.setJmxNameBase("handles");
        handlePool = new CublasHandlePool(new CublasHandlePooledItemFactory(), config);
        GenericObjectPoolConfig confClone = config.clone();
        confClone.setMaxTotal(Runtime.getRuntime().availableProcessors() * 10);
        confClone.setMaxIdle(Runtime.getRuntime().availableProcessors() * 10);
        confClone.setMinIdle(Runtime.getRuntime().availableProcessors() * 10);
        GenericObjectPoolConfig streamConf = confClone.clone();
        streamConf.setJmxNameBase("streams");
        streamPool = new StreamPool(new StreamItemFactory(), streamConf);
        GenericObjectPoolConfig oldStreamConf = streamConf.clone();
        oldStreamConf.setJmxNameBase("oldstream");
        oldStreamPool = new OldStreamPool(new OldStreamItemFactory(), oldStreamConf);
        setContext();
        //seed with multiple streams to encourage parallelism
        for (int i = 0; i < Runtime.getRuntime().availableProcessors(); i++) {
            streamPool.addObject();
            oldStreamPool.addObject();
        }

        //force context initialization to occur
        JCuda.cudaFree(Pointer.to(new int[] { 0 }));

    } catch (Exception e) {
        log.warn("Unable to initialize cuda", e);
    }

    for (int i = 0; i < numDevices; i++) {
        ClassPathResource confFile = new ClassPathResource("devices/" + i,
                ContextHolder.class.getClassLoader());
        if (confFile.exists()) {
            Properties props2 = new Properties();
            try {
                props2.load(confFile.getInputStream());
                confs.put(i, new DeviceConfiguration(i, props2));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        } else
            confs.put(i, new DeviceConfiguration(i));

    }

    confCalled = true;
}