java - 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();
}
}
}
知道为什么即使它们在不同的线程中它也不并行运行吗?
解决方案
推荐阅读
- couchdb - 由于修订,CouchDB 占用了大量空间
- python - 如何写入子目录 Python 2.7 中的文件?
- tensorflow - 验证集上的去噪自动编码器给出了不好的结果,甚至对于训练图像在实例中随机噪声
- python - 如何解决 FileNotFoundError: [Errno 2] No such file or directory for Python 3.7/Mac
- javascript - 以特定格式将 mysql 数据检索到 javascript 的问题
- python - 编写一个算法来计算字典中子字典的数量
- javascript - 在javascript中将IST缩写解析为+0530
- python - urllib.error.HTTPError:HTTP 错误 404:从 Metacritic 抓取数据时未找到 Python
- mysql - 除了“数量”之外,所有列都给出了正确的值 - 使用 MySQL WITH ROLLUP
- react-native - 如何在导航参数中传递获取响应?