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.