Search in sources :

Example 66 with HikariDataSource

use of com.zaxxer.hikari.HikariDataSource in project HikariCP by brettwooldridge.

the class ConcurrentCloseConnectionTest method testConcurrentClose.

@Test
public void testConcurrentClose() throws Exception {
    HikariConfig config = newHikariConfig();
    config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
    try (HikariDataSource ds = new HikariDataSource(config);
        final Connection connection = ds.getConnection()) {
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        List<Future<?>> futures = new ArrayList<>();
        for (int i = 0; i < 500; i++) {
            final PreparedStatement preparedStatement = connection.prepareStatement("");
            futures.add(executorService.submit(new Callable<Void>() {

                @Override
                public Void call() throws Exception {
                    preparedStatement.close();
                    return null;
                }
            }));
        }
        executorService.shutdown();
        for (Future<?> future : futures) {
            future.get();
        }
    }
}
Also used : HikariDataSource(com.zaxxer.hikari.HikariDataSource) Connection(java.sql.Connection) ExecutorService(java.util.concurrent.ExecutorService) ArrayList(java.util.ArrayList) Future(java.util.concurrent.Future) PreparedStatement(java.sql.PreparedStatement) HikariConfig(com.zaxxer.hikari.HikariConfig) TestElf.newHikariConfig(com.zaxxer.hikari.pool.TestElf.newHikariConfig) Callable(java.util.concurrent.Callable) Test(org.junit.Test)

Example 67 with HikariDataSource

use of com.zaxxer.hikari.HikariDataSource in project HikariCP by brettwooldridge.

the class ConnectionPoolSizeVsThreadsTest method testPoolSize.

private Counts testPoolSize(final int minIdle, final int maxPoolSize, final int threadCount, final long workTimeMs, final long restTimeMs, final long connectionAcquisitionTimeMs, final int iterations, final long postTestTimeMs) throws Exception {
    LOGGER.info("Starting test (minIdle={}, maxPoolSize={}, threadCount={}, workTimeMs={}, restTimeMs={}, connectionAcquisitionTimeMs={}, iterations={}, postTestTimeMs={})", minIdle, maxPoolSize, threadCount, workTimeMs, restTimeMs, connectionAcquisitionTimeMs, iterations, postTestTimeMs);
    final HikariConfig config = newHikariConfig();
    config.setMinimumIdle(minIdle);
    config.setMaximumPoolSize(maxPoolSize);
    config.setInitializationFailTimeout(Long.MAX_VALUE);
    config.setConnectionTimeout(2500);
    config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
    final AtomicReference<Exception> ref = new AtomicReference<>(null);
    // Initialize HikariPool with no initial connections and room to grow
    try (final HikariDataSource ds = new HikariDataSource(config)) {
        final StubDataSource stubDataSource = ds.unwrap(StubDataSource.class);
        // connection acquisition takes more than 0 ms in a real system
        stubDataSource.setConnectionAcquistionTime(connectionAcquisitionTimeMs);
        final ExecutorService threadPool = newFixedThreadPool(threadCount);
        final CountDownLatch allThreadsDone = new CountDownLatch(iterations);
        for (int i = 0; i < iterations; i++) {
            threadPool.submit(() -> {
                if (ref.get() == null) {
                    quietlySleep(restTimeMs);
                    try (Connection c2 = ds.getConnection()) {
                        quietlySleep(workTimeMs);
                    } catch (Exception e) {
                        ref.set(e);
                    }
                }
                allThreadsDone.countDown();
            });
        }
        final HikariPool pool = getPool(ds);
        // collect pool usage data while work is still being done
        final Counts underLoad = new Counts();
        while (allThreadsDone.getCount() > 0 || pool.getTotalConnections() < minIdle) {
            quietlySleep(50);
            underLoad.updateMaxCounts(pool);
        }
        // wait for long enough any pending acquisitions have already been done
        LOGGER.info("Test Over, waiting for post delay time {}ms ", postTestTimeMs);
        quietlySleep(connectionAcquisitionTimeMs + workTimeMs + restTimeMs);
        // collect pool data while there is no work to do.
        final Counts postLoad = new Counts();
        final long start = currentTime();
        while (elapsedMillis(start) < postTestTimeMs) {
            quietlySleep(50);
            postLoad.updateMaxCounts(pool);
        }
        allThreadsDone.await();
        threadPool.shutdown();
        threadPool.awaitTermination(30, SECONDS);
        if (ref.get() != null) {
            LOGGER.error("Task failed", ref.get());
            fail("Task failed");
        }
        LOGGER.info("Under Load... {}", underLoad);
        LOGGER.info("Post Load.... {}", postLoad);
        // verify that the no connections created after the work has stopped
        if (postTestTimeMs > 0) {
            if (postLoad.maxActive != 0) {
                fail("Max Active was greater than 0 after test was done");
            }
            final int createdAfterWorkAllFinished = postLoad.maxTotal - underLoad.maxTotal;
            assertEquals("Connections were created when there was no waiting consumers", 0, createdAfterWorkAllFinished, 1);
        }
        return underLoad;
    }
}
Also used : HikariDataSource(com.zaxxer.hikari.HikariDataSource) Connection(java.sql.Connection) AtomicReference(java.util.concurrent.atomic.AtomicReference) HikariConfig(com.zaxxer.hikari.HikariConfig) TestElf.newHikariConfig(com.zaxxer.hikari.pool.TestElf.newHikariConfig) CountDownLatch(java.util.concurrent.CountDownLatch) ExecutorService(java.util.concurrent.ExecutorService) StubDataSource(com.zaxxer.hikari.mocks.StubDataSource)

Example 68 with HikariDataSource

use of com.zaxxer.hikari.HikariDataSource in project HikariCP by brettwooldridge.

the class ConnectionRaceConditionTest method testRaceCondition.

@Test
public void testRaceCondition() throws Exception {
    HikariConfig config = newHikariConfig();
    config.setMinimumIdle(0);
    config.setMaximumPoolSize(10);
    config.setInitializationFailTimeout(Long.MAX_VALUE);
    config.setConnectionTimeout(2500);
    config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
    setSlf4jLogLevel(ConcurrentBag.class, Level.INFO);
    final AtomicReference<Exception> ref = new AtomicReference<>(null);
    // Initialize HikariPool with no initial connections and room to grow
    try (final HikariDataSource ds = new HikariDataSource(config)) {
        ExecutorService threadPool = Executors.newFixedThreadPool(2);
        for (int i = 0; i < ITERATIONS; i++) {
            threadPool.submit(new Callable<Exception>() {

                /** {@inheritDoc} */
                @Override
                public Exception call() throws Exception {
                    if (ref.get() == null) {
                        Connection c2;
                        try {
                            c2 = ds.getConnection();
                            ds.evictConnection(c2);
                        } catch (Exception e) {
                            ref.set(e);
                        }
                    }
                    return null;
                }
            });
        }
        threadPool.shutdown();
        threadPool.awaitTermination(30, TimeUnit.SECONDS);
        if (ref.get() != null) {
            LoggerFactory.getLogger(ConnectionRaceConditionTest.class).error("Task failed", ref.get());
            fail("Task failed");
        }
    } catch (Exception e) {
        throw e;
    }
}
Also used : HikariDataSource(com.zaxxer.hikari.HikariDataSource) ExecutorService(java.util.concurrent.ExecutorService) Connection(java.sql.Connection) AtomicReference(java.util.concurrent.atomic.AtomicReference) HikariConfig(com.zaxxer.hikari.HikariConfig) TestElf.newHikariConfig(com.zaxxer.hikari.pool.TestElf.newHikariConfig) Test(org.junit.Test)

Example 69 with HikariDataSource

use of com.zaxxer.hikari.HikariDataSource in project HikariCP by brettwooldridge.

the class ConnectionStateTest method testCommitTracking.

@Test
public void testCommitTracking() throws SQLException {
    try (HikariDataSource ds = newHikariDataSource()) {
        ds.setAutoCommit(false);
        ds.setMinimumIdle(1);
        ds.setMaximumPoolSize(1);
        ds.setConnectionTestQuery("VALUES 1");
        ds.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
        try (Connection connection = ds.getConnection()) {
            Statement statement = connection.createStatement();
            statement.execute("SELECT something");
            assertTrue(TestElf.getConnectionCommitDirtyState(connection));
            connection.commit();
            assertFalse(TestElf.getConnectionCommitDirtyState(connection));
            statement.execute("SELECT something", Statement.NO_GENERATED_KEYS);
            assertTrue(TestElf.getConnectionCommitDirtyState(connection));
            connection.rollback();
            assertFalse(TestElf.getConnectionCommitDirtyState(connection));
            ResultSet resultSet = statement.executeQuery("SELECT something");
            assertTrue(TestElf.getConnectionCommitDirtyState(connection));
            connection.rollback(null);
            assertFalse(TestElf.getConnectionCommitDirtyState(connection));
            resultSet.updateRow();
            assertTrue(TestElf.getConnectionCommitDirtyState(connection));
        }
    }
}
Also used : TestElf.newHikariDataSource(com.zaxxer.hikari.pool.TestElf.newHikariDataSource) HikariDataSource(com.zaxxer.hikari.HikariDataSource) Statement(java.sql.Statement) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) Test(org.junit.Test)

Example 70 with HikariDataSource

use of com.zaxxer.hikari.HikariDataSource in project HikariCP by brettwooldridge.

the class ConnectionStateTest method testReadOnly.

@Test
public void testReadOnly() throws Exception {
    try (HikariDataSource ds = newHikariDataSource()) {
        ds.setCatalog("test");
        ds.setMinimumIdle(1);
        ds.setMaximumPoolSize(1);
        ds.setConnectionTestQuery("VALUES 1");
        ds.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
        try (Connection connection = ds.getConnection()) {
            Connection unwrap = connection.unwrap(Connection.class);
            connection.setReadOnly(true);
            connection.close();
            assertFalse(unwrap.isReadOnly());
        }
    }
}
Also used : TestElf.newHikariDataSource(com.zaxxer.hikari.pool.TestElf.newHikariDataSource) HikariDataSource(com.zaxxer.hikari.HikariDataSource) Connection(java.sql.Connection) Test(org.junit.Test)

Aggregations

HikariDataSource (com.zaxxer.hikari.HikariDataSource)114 Test (org.junit.Test)78 HikariConfig (com.zaxxer.hikari.HikariConfig)75 TestElf.newHikariConfig (com.zaxxer.hikari.pool.TestElf.newHikariConfig)63 Connection (java.sql.Connection)63 TestElf.newHikariDataSource (com.zaxxer.hikari.pool.TestElf.newHikariDataSource)33 StubConnection (com.zaxxer.hikari.mocks.StubConnection)29 SQLException (java.sql.SQLException)27 TestElf.setConfigUnitTest (com.zaxxer.hikari.pool.TestElf.setConfigUnitTest)16 StubDataSource (com.zaxxer.hikari.mocks.StubDataSource)10 MetricRegistry (com.codahale.metrics.MetricRegistry)8 PreparedStatement (java.sql.PreparedStatement)6 Statement (java.sql.Statement)6 PoolInitializationException (com.zaxxer.hikari.pool.HikariPool.PoolInitializationException)5 SQLTransientConnectionException (java.sql.SQLTransientConnectionException)5 Properties (java.util.Properties)5 ResultSet (java.sql.ResultSet)4 HealthCheckRegistry (com.codahale.metrics.health.HealthCheckRegistry)3 ArrayList (java.util.ArrayList)3 ExecutorService (java.util.concurrent.ExecutorService)3