List of usage examples for org.apache.commons.dbcp BasicDataSource setInitialSize
public synchronized void setInitialSize(int initialSize)
Sets the initial size of the connection pool.
Note: this method currently has no effect once the pool has been initialized.
From source file:com.jolbox.benchmark.BenchmarkTests.java
/** * /*from w ww . ja v a 2s.c om*/ * * @return time taken * @throws SQLException */ private long singleDBCP() throws SQLException { // Start DBCP BasicDataSource cpds = new BasicDataSource(); cpds.setDriverClassName("com.jolbox.bonecp.MockJDBCDriver"); cpds.setUrl(url); cpds.setUsername(username); cpds.setPassword(password); cpds.setMaxIdle(-1); cpds.setMinIdle(-1); cpds.setMaxOpenPreparedStatements(max_statement); cpds.setInitialSize(pool_size); cpds.setMaxActive(pool_size); cpds.getConnection(); // call to initialize possible lazy structures etc long start = System.currentTimeMillis(); for (int i = 0; i < MAX_CONNECTIONS; i++) { Connection conn = cpds.getConnection(); conn.close(); } long end = (System.currentTimeMillis() - start); // System.out.println("DBCP Single thread benchmark: "+end); cpds.close(); return end; }
From source file:com.headstrong.fusion.services.dbpool.impl.DbPool.java
/** * package level constructor to create new dbpool instance. * /*from w w w .ja v a 2 s.c o m*/ * @param props * properties that needs to be set for creating the pool. * @throws FusionException * Error initializing dbpool */ /* package */ DbPool(Map<String, String> props, String dbcp) throws FusionException { BasicDataSource basicDataSource = new BasicDataSource(); if (dbProps == null) { dbProps = new HashMap<String, String>(props); } if (checkMandatoryProperties(props)) { basicDataSource.setDriverClassName(props.get(FusionConstants.DATABASE_CLASSNAME)); basicDataSource.setUsername(props.get(FusionConstants.DATABASE_USERNAME)); basicDataSource.setPassword(props.get(FusionConstants.DATABASE_PASSWORD)); basicDataSource.setUrl(props.get(FusionConstants.DATABASE_URL)); basicDataSource.setMinEvictableIdleTimeMillis(this.MINEVICTABLEIDLETIMEMILLIS); basicDataSource.setTimeBetweenEvictionRunsMillis(this.TIMEBETWEENEVICTIONRUNSMILLIS); String JDBCINITIALSIZE = props.get(FusionConstants.JDBCINITIALSIZE) != null ? props.get(FusionConstants.JDBCINITIALSIZE) : dbProps.get(FusionConstants.JDBCINITIALSIZE); basicDataSource.setInitialSize(Integer.parseInt(JDBCINITIALSIZE)); String JDBCMAXACTIVE = props.get(FusionConstants.JDBCMAXACTIVE) != null ? props.get(FusionConstants.JDBCMAXACTIVE) : dbProps.get(FusionConstants.JDBCMAXACTIVE); basicDataSource.setMaxActive(Integer.parseInt(JDBCMAXACTIVE)); String JDBCMAXOPENACTIVEPREP = props.get(FusionConstants.JDBCMAXOPENACTIVEPREP) != null ? props.get(FusionConstants.JDBCMAXOPENACTIVEPREP) : dbProps.get(FusionConstants.JDBCMAXOPENACTIVEPREP); basicDataSource.setMaxOpenPreparedStatements(Integer.parseInt(JDBCMAXOPENACTIVEPREP)); String MINEVICTABLEIDLETIMEMILLIS = props.get(FusionConstants.MINEVICTABLEIDLETIMEMILLIS) != null ? props.get(FusionConstants.MINEVICTABLEIDLETIMEMILLIS) : dbProps.get(FusionConstants.MINEVICTABLEIDLETIMEMILLIS); basicDataSource.setMinEvictableIdleTimeMillis(Integer.parseInt(MINEVICTABLEIDLETIMEMILLIS)); String TIMEBETWEENEVICTIONRUNSMILLIS = props.get(FusionConstants.TIMEBETWEENEVICTIONRUNSMILLIS) != null ? props.get(FusionConstants.TIMEBETWEENEVICTIONRUNSMILLIS) : dbProps.get(FusionConstants.TIMEBETWEENEVICTIONRUNSMILLIS); basicDataSource.setTimeBetweenEvictionRunsMillis(Long.parseLong(TIMEBETWEENEVICTIONRUNSMILLIS)); /* * if (props.get(FusionConstants.JDBCINITIALSIZE) == null) { * basicDataSource.setInitialSize(Integer.parseInt(dbProps * .get(FusionConstants.JDBCINITIALSIZE))); } else { * basicDataSource.setInitialSize(Integer.parseInt(props * .get(FusionConstants.JDBCINITIALSIZE))); } if * (props.get(FusionConstants.JDBCMAXACTIVE) == null) { * basicDataSource.setInitialSize(Integer.parseInt(dbProps * .get(FusionConstants.JDBCMAXACTIVE))); } else { * basicDataSource.setInitialSize(Integer.parseInt(props * .get(FusionConstants.JDBCMAXACTIVE))); } if * (props.get(FusionConstants.JDBCMAXOPENACTIVEPREP) == null) { * basicDataSource.setInitialSize(Integer.parseInt(dbProps * .get(FusionConstants.JDBCMAXOPENACTIVEPREP))); } else { * basicDataSource.setInitialSize(Integer.parseInt(props * .get(FusionConstants.JDBCMAXOPENACTIVEPREP))); } * * if (props.get(FusionConstants.MINEVICTABLEIDLETIMEMILLIS) == * null) { basicDataSource.setInitialSize(Integer.parseInt(dbProps * .get(FusionConstants.MINEVICTABLEIDLETIMEMILLIS))); } else { * basicDataSource.setInitialSize(Integer.parseInt(props * .get(FusionConstants.MINEVICTABLEIDLETIMEMILLIS))); } if * (props.get(FusionConstants.TIMEBETWEENEVICTIONRUNSMILLIS) == * null) { basicDataSource.setInitialSize(Integer.parseInt(dbProps * .get(FusionConstants.TIMEBETWEENEVICTIONRUNSMILLIS))); } else { * basicDataSource.setInitialSize(Integer.parseInt(props * .get(FusionConstants.TIMEBETWEENEVICTIONRUNSMILLIS))); } */ dataSource = basicDataSource; } else { throw new FusionException("Error initializing dbpool"); } }
From source file:com.jolbox.benchmark.BenchmarkTests.java
/** * Benchmarks PreparedStatement functionality (single thread) * @return result/*from www . j a v a 2 s . co m*/ * * @throws PropertyVetoException * @throws SQLException */ private long testPreparedStatementSingleThreadDBCP() throws PropertyVetoException, SQLException { BasicDataSource cpds = new BasicDataSource(); cpds.setDriverClassName("com.jolbox.bonecp.MockJDBCDriver"); cpds.setUrl(url); cpds.setUsername(username); cpds.setPassword(password); cpds.setMaxIdle(-1); cpds.setMinIdle(-1); cpds.setPoolPreparedStatements(true); cpds.setMaxOpenPreparedStatements(30); cpds.setInitialSize(pool_size); cpds.setMaxActive(pool_size); Connection conn = cpds.getConnection(); long start = System.currentTimeMillis(); for (int i = 0; i < MAX_CONNECTIONS; i++) { Statement st = conn.prepareStatement(TEST_QUERY); st.close(); } conn.close(); long end = (System.currentTimeMillis() - start); System.out.println("DBCP PreparedStatement Single thread benchmark: " + end); results.add("DBCP, " + end); // dispose of pool cpds.close(); return end; }
From source file:com.jolbox.benchmark.BenchmarkTests.java
/** * //from ww w . j a va 2 s . co m * * @param doPreparedStatement * @return time taken * @throws PropertyVetoException * @throws InterruptedException * @throws SQLException */ private DataSource multiThreadedDBCP(boolean doPreparedStatement) throws PropertyVetoException, InterruptedException, SQLException { BasicDataSource cpds = new BasicDataSource(); cpds.setDriverClassName("com.jolbox.bonecp.MockJDBCDriver"); cpds.setUrl(url); cpds.setUsername(username); cpds.setPassword(password); cpds.setMaxIdle(-1); cpds.setMinIdle(-1); if (doPreparedStatement) { cpds.setPoolPreparedStatements(true); cpds.setMaxOpenPreparedStatements(max_statement); } cpds.setInitialSize(pool_size); cpds.setMaxActive(pool_size); return cpds; }
From source file:com.bstek.dorado.core.store.SqlBaseStoreSupport.java
protected synchronized DataSource getDataSource() throws Exception { if (dataSource != null) { return dataSource; }/*from w w w . j a v a 2 s . c o m*/ if (StringUtils.isBlank(namespace)) { throw new IllegalArgumentException("The namespace of store cannot be empty. "); } prepareNamespace(); BasicDataSource pds = new BasicDataSource(); dataSource = pds; pds.setDriverClassName(driverClassName); pds.setUrl(getConnectionUrl()); pds.setUsername(username); pds.setPassword(password); pds.setDefaultCatalog(defaultCatalog); if (defaultAutoCommit != null) { pds.setDefaultAutoCommit(defaultAutoCommit.booleanValue()); } if (defaultReadOnly != null) { pds.setDefaultReadOnly(defaultReadOnly.booleanValue()); } if (defaultTransactionIsolation != null) { pds.setDefaultTransactionIsolation(defaultTransactionIsolation.intValue()); } if (maxActive != null) { pds.setMaxActive(maxActive.intValue()); } if (maxIdle != null) { pds.setMaxIdle(maxIdle.intValue()); } if (minIdle != null) { pds.setMinIdle(minIdle.intValue()); } if (initialSize != null) { pds.setInitialSize(initialSize.intValue()); } if (maxWait != null) { pds.setMaxWait(maxWait.longValue()); } if (timeBetweenEvictionRunsMillis != null) { pds.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis.longValue()); } if (minEvictableIdleTimeMillis != null) { pds.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis.longValue()); } return dataSource; }
From source file:jetsennet.orm.datasource.DbcpDataSourceCreator.java
@Override public DataSource createDatasource(ConnectionInfo conn, DbPoolInfo props) throws SQLException { org.apache.commons.dbcp.BasicDataSource dataSource = new org.apache.commons.dbcp.BasicDataSource(); dataSource.setDriverClassName(conn.driver); dataSource.setUrl(conn.url);//w w w. j a v a 2 s.c o m dataSource.setUsername(conn.user); dataSource.setPassword(conn.pwd); String connectionProperties = props.get("connectionProperties"); if (connectionProperties != null && connectionProperties.trim().length() > 0) { dataSource.setConnectionProperties(connectionProperties); } Boolean defaultAutoCommit = Utils.str2Boolean(props.get("defaultAutoCommit")); if (defaultAutoCommit != null) { dataSource.setDefaultAutoCommit(defaultAutoCommit); } Boolean defaultReadOnly = Utils.str2Boolean(props.get("defaultReadOnly")); if (defaultReadOnly != null) { dataSource.setDefaultReadOnly(defaultReadOnly); } Integer defaultTransactionIsolation = Utils.strToInteger(props.get("defaultTransactionIsolation")); if (defaultTransactionIsolation != null) { dataSource.setDefaultTransactionIsolation(defaultTransactionIsolation); } String defaultCatalog = props.get("defaultCatalog"); if (defaultCatalog != null && defaultCatalog.trim().length() > 0) { dataSource.setDefaultCatalog(defaultCatalog); } int initialSize = Utils.strToInt(props.get("initialSize")); if (initialSize > 0) { dataSource.setInitialSize(initialSize); } int maxActive = Utils.strToInt(props.get("maxActive")); if (maxActive > 0) { dataSource.setMaxActive(maxActive); } int maxIdle = Utils.strToInt(props.get("maxIdle")); if (maxIdle > 0) { dataSource.setMaxIdle(maxIdle); } int minIdle = Utils.strToInt(props.get("minIdle")); if (minIdle > 0) { dataSource.setMinIdle(minIdle); } int maxWait = Utils.strToInt(props.get("maxWait")); if (maxWait > 0) { dataSource.setMaxWait(maxWait); } String validationQuery = props.get("validationQuery"); if (validationQuery != null && validationQuery.trim().length() > 0) { dataSource.setValidationQuery(validationQuery); } Integer validationQueryTimeout = Utils.strToInteger(props.get("validationQueryTimeout")); if (validationQueryTimeout != null) { dataSource.setValidationQueryTimeout(validationQueryTimeout); } Boolean testOnBorrow = Utils.str2Boolean(props.get("testOnBorrow")); if (testOnBorrow != null) { dataSource.setTestOnBorrow(testOnBorrow); } Boolean testOnReturn = Utils.str2Boolean(props.get("testOnReturn")); if (testOnReturn != null) { dataSource.setTestOnReturn(testOnReturn); } Boolean testWhileIdle = Utils.str2Boolean(props.get("testWhileIdle")); if (testWhileIdle != null) { dataSource.setTestWhileIdle(testWhileIdle); } Integer timeBetweenEvictionRunsMillis = Utils.strToInteger(props.get("timeBetweenEvictionRunsMillis")); if (timeBetweenEvictionRunsMillis != null) { dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis); } Integer numTestsPerEvictionRun = Utils.strToInteger(props.get("numTestsPerEvictionRun")); if (numTestsPerEvictionRun != null) { dataSource.setNumTestsPerEvictionRun(numTestsPerEvictionRun); } int minEvictableIdleTimeMillis = Utils.strToInt(props.get("minEvictableIdleTimeMillis")); if (minEvictableIdleTimeMillis > 0) { dataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis); } Boolean removeAbandoned = Utils.str2Boolean(props.get("removeAbandoned")); if (removeAbandoned != null) { dataSource.setRemoveAbandoned(removeAbandoned); } int removeAbandonedTimeout = Utils.strToInt(props.get("removeAbandonedTimeout")); if (removeAbandonedTimeout > 0) { dataSource.setRemoveAbandonedTimeout(removeAbandonedTimeout); } Boolean logAbandoned = Utils.str2Boolean(props.get("logAbandoned")); if (logAbandoned != null) { dataSource.setLogAbandoned(logAbandoned); } return dataSource; }
From source file:org.apache.drill.exec.store.http.InsertTestData.java
public static DataSource createDataSource(String driver, String url, String userName, String password) { BasicDataSource source = new BasicDataSource(); source.setDriverClassName(driver);//from www . ja v a2 s . c om source.setUrl(url); if (userName != null) { source.setUsername(userName); } if (password != null) { source.setPassword(password); } source.setInitialSize(1); source.setPoolPreparedStatements(true); try { // initial a connection source.getConnection(); } catch (SQLException sqlE) { logger.error("db connection error: ", sqlE); } return source; }
From source file:org.apache.drill.exec.store.http.util.DBUtil.java
public static DataSource createDataSource(String driver, String url, String userName, String password) { BasicDataSource source = new BasicDataSource(); source.setDriverClassName(driver);// w ww.java 2 s .c om source.setUrl(url); if (userName != null) { source.setUsername(userName); } if (password != null) { source.setPassword(password); } source.setPoolPreparedStatements(true); source.setInitialSize(1); try { // initial a connection Connection conn = source.getConnection(); conn.close(); } catch (SQLException sqlE) { logger.error("db connection error: ", sqlE); } return source; }
From source file:org.apache.metamodel.jdbc.JdbcDataContextTest.java
public void testReleaseConnectionsInCompiledQuery() throws Exception { final int connectionPoolSize = 2; final int threadCount = 4; final int noOfCallsPerThreads = 30; final BasicDataSource ds = new BasicDataSource(); ds.setDriverClassName("org.hsqldb.jdbcDriver"); ds.setUrl("jdbc:hsqldb:res:metamodel"); ds.setInitialSize(connectionPoolSize); ds.setMaxActive(connectionPoolSize); ds.setMaxWait(10000);//w w w . j a v a 2 s. co m ds.setMinEvictableIdleTimeMillis(1800000); ds.setMinIdle(0); ds.setMaxIdle(connectionPoolSize); ds.setNumTestsPerEvictionRun(3); ds.setTimeBetweenEvictionRunsMillis(-1); ds.setDefaultTransactionIsolation(java.sql.Connection.TRANSACTION_READ_COMMITTED); final JdbcDataContext dataContext = new JdbcDataContext(ds, new TableType[] { TableType.TABLE, TableType.VIEW }, null); final JdbcCompiledQuery compiledQuery = (JdbcCompiledQuery) dataContext.query().from("CUSTOMERS") .select("CUSTOMERNAME").where("CUSTOMERNUMBER").eq(new QueryParameter()).compile(); assertEquals(0, compiledQuery.getActiveLeases()); assertEquals(0, compiledQuery.getIdleLeases()); final String compliedQueryString = compiledQuery.toSql(); assertEquals( "SELECT _CUSTOMERS_._CUSTOMERNAME_ FROM PUBLIC._CUSTOMERS_ WHERE _CUSTOMERS_._CUSTOMERNUMBER_ = ?", compliedQueryString.replace('\"', '_')); assertEquals(0, compiledQuery.getActiveLeases()); assertEquals(0, compiledQuery.getIdleLeases()); ExecutorService executorService = Executors.newFixedThreadPool(threadCount); final CountDownLatch latch = new CountDownLatch(threadCount); final List<Throwable> errors = new ArrayList<Throwable>(); final Runnable runnable = new Runnable() { @Override public void run() { try { for (int i = 0; i < noOfCallsPerThreads; i++) { final DataSet dataSet = dataContext.executeQuery(compiledQuery, new Object[] { 103 }); try { assertTrue(dataSet.next()); Row row = dataSet.getRow(); assertNotNull(row); assertEquals("Atelier graphique", row.getValue(0).toString()); assertFalse(dataSet.next()); } finally { dataSet.close(); } } } catch (Throwable e) { errors.add(e); } finally { latch.countDown(); } } }; for (int i = 0; i < threadCount; i++) { executorService.execute(runnable); } try { latch.await(60000, TimeUnit.MILLISECONDS); if (errors.size() > 0) { throw new IllegalStateException(errors.get(0)); } assertTrue(true); } finally { executorService.shutdownNow(); } assertEquals(0, compiledQuery.getActiveLeases()); compiledQuery.close(); assertEquals(0, compiledQuery.getActiveLeases()); assertEquals(0, compiledQuery.getIdleLeases()); }
From source file:org.apache.metamodel.jdbc.JdbcUpdateCallbackTest.java
@Test public void testTransactionalUpdateScripts() throws Exception { DerbyTest.initDerbySettings();/*from w w w . j a v a 2 s . com*/ final BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName("org.apache.derby.jdbc.EmbeddedDriver"); dataSource.setUrl("jdbc:derby:target/temp_derby;create=true"); dataSource.setInitialSize(10); dataSource.setMaxActive(10); dataSource.setMaxWait(10000); dataSource.setMinEvictableIdleTimeMillis(1800000); dataSource.setMinIdle(0); dataSource.setMaxIdle(10); dataSource.setNumTestsPerEvictionRun(3); dataSource.setTimeBetweenEvictionRunsMillis(-1); dataSource.setDefaultTransactionIsolation(ISOLATION_LEVEL); final String tableName = "counter_table"; final String columnName = "n"; final JdbcDataContext dataContext = new JdbcDataContext(dataSource); dataContext.executeUpdate(new UpdateScript() { @Override public void run(UpdateCallback callback) { if (dataContext.getTableByQualifiedLabel(tableName) != null) { callback.dropTable(tableName).execute(); } callback.createTable(dataContext.getDefaultSchema(), tableName).withColumn(columnName) .ofType(ColumnType.INTEGER).execute(); } }); final Table table = dataContext.getTableByQualifiedLabel(tableName); final Column col = table.getColumnByName(columnName); assertNotNull(col); // insert one record - this one record will be updated transactionally below dataContext.executeUpdate(new InsertInto(table).value(columnName, 0)); final UpdateScript updateScript = new UpdateScript() { @Override public void run(UpdateCallback callback) { final int n = getCounterValue(callback.getDataContext(), table, col); callback.update(table).value(col, n + 1).execute(); } }; final int threadCount = 2; final int iterationsPerThread = 5; final Thread[] threads = new Thread[threadCount]; for (int i = 0; i < threads.length; i++) { threads[i] = new Thread() { @Override public void run() { for (int j = 0; j < iterationsPerThread; j++) { int retries = 10; while (retries > 0) { try { dataContext.executeUpdate(updateScript); retries = 0; } catch (RolledBackUpdateException e) { retries--; if (retries == 0) { throw e; } } } } } }; } for (Thread thread : threads) { thread.start(); } for (Thread thread : threads) { thread.join(); } assertEquals(threadCount * iterationsPerThread, getCounterValue(dataContext, table, col)); }