Understanding JdbcConnectionPool with an H2 Database

I have an H2 server process running on my main server machine that allows you to use TCP connections.

Let's say I want to execute 100 SQL queries:

SELECT * FROM TEST

And, for my own purposes, I want to make one request per thread. Let me do this with one and only one Connectionobject shared between threads:

  • Create one object Connection.
  • Create 100 threads.
  • In each thread, use a shared object Connectionto invoke the SQL query.

The above will work, but it will be a little slow. Of course, in the end, if someone uses it Connection, then the rest should wait for it.

Ok, then do one Connectionper thread:

  • Create 100 threads.
  • Connection SQL.

, . , 100 - . , 50 . , JdbcConnectionPool .

  • JdbcConnectionPool 50 .
  • 100 .
  • pool.getConnection(), SQL-.

. . , , . , , 100...

... . Weird. , 100 100 .

? :

import java.sql.Connection;
import java.sql.ResultSet;

import org.h2.jdbcx.JdbcConnectionPool;

public class App {

    public static void main(String[] args) throws Exception {
        Class.forName("org.h2.Driver");
        JdbcConnectionPool pool = JdbcConnectionPool.create("url", "user", "password");
        pool.setMaxConnections(100);
        for (int i = 0; i < 100; ++i) {
            Thread t = new Thread(new Client(i, pool));
            t.start();
        }
    }
}

class Client implements Runnable {
    int id;
    JdbcConnectionPool pool;
    public Client(int id, JdbcConnectionPool pool) {
        this.id = id;
        this.pool = pool;
    }
    public void run() {
        try {
            Connection conn = pool.getConnection();
            ResultSet set = conn.createStatement().executeQuery("SELECT * FROM TEST");
            if (set.next()) {
                System.out.println("Finished " + id);
            }
            set.close();
            conn.close();
        }catch (Exception e) {

        }
    }
}

H2 1.4.182.

+4
1

JdbcConnectionPool # getConnection():

  public Connection getConnection() throws SQLException {
        long max = System.currentTimeMillis() + timeout * 1000;
        do {
              synchronized (this){
                if (activeConnections < maxConnections) {
                    return getConnectionNow();
                }
                try {
                    wait(1000);
                } catch (InterruptedException e) {
                    // ignore
                }
            }
        } while (System.currentTimeMillis() <= max);
        throw new SQLException("Login timeout", "08001", 8001);
    }

- . , getConnection() (), .

, h2 . , C3P0 BoneCP.

+2

All Articles