首页 > 解决方案 > JDBC顺序PreparedStatement?

问题描述

进行以下测试时,我注意到 PreparedStatement 正在按顺序运行,这可能吗?有没有办法并行运行它?

我正在创建一个连接列表,然后创建多个线程(与我的连接一样多)并运行 PreparedStatement。

我看到查询的执行可能是并行的,因为我打印的时间是增量的(而不是相同的近似值)。第一个线程给了我 3 秒的时间,并且它不断增加,直到达到 20-30 秒。

@Test
void test2() {
    for(int i = 0; i < MYTHREADS; i++) {
        try {
            Connection connection = DriverManager.getConnection(
                    "jdbc:postgresql://url:port/db?ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory&sslmode=require",
                    "usr", "pwd");
            connection.setSchema("schema");
            connectionList.add(connection);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
    for(int i = 0; i < connectionList.size(); i++) {
        Runnable worker = new MyRunnable(i);
        executor.execute(worker);
    }
    executor.shutdown();
    // Wait until all threads are finish
    while (!executor.isTerminated()) {}
}

private static class MyRunnable implements Runnable {

    private final int connectionNumber;

    public MyRunnable2(int connectionNumber) {
        this.connectionNumber = connectionNumber;
    }

    @Override
    public void run() {
        try {
            String sentence = "SELECT * FROM X WHERE date >= ? AND date <= ? AND client = ? ORDER BY date ASC LIMIT 5000 OFFSET 0;";
            PreparedStatement preparedStatement = connectionList.get(connectionNumber).prepareStatement(sentence);
            preparedStatement.setObject(1, 0);
            preparedStatement.setObject(2, System.currentTimeMillis());
            preparedStatement.setObject(3, "75");

            long initialTime = System.currentTimeMillis();
            ResultSet resultSet = preparedStatement.executeQuery();
            log.info("Time ({}): {}", Thread.currentThread().getName(), System.currentTimeMillis() - initialTime);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}

知道为什么即使它们在不同的线程中它也不并行运行吗?

标签: javapostgresqlmultithreadingjdbc

解决方案


推荐阅读