我正在尝试从 Java 应用程序在 Oracle 数据库中并行进行多个读取查询。我使用 CallableTasks 进行这些查询。Callable Task的样例如下:
public class MyCallableTask<T> implements Callable<List<T>> {
private String sql;
private Connection connection;
private Class<T> classInstance;
public MyCallableTask(String sql, Connection connection, Class<T> classInstance) {
// the connection object is sent here from a db connection pool, so that each callable has its own connection instance.
this.connection = connection;
this.sql = sql;
this.classInstance = classInstance;
}
@Override
public List<T> call() throws Exception {
PreparedStatement ps = connection.createPreparedStatement(sql);
Resultset rs = ps.executeQuery();
// Using commons-dbutils resultsethandler to map the resultset to a Java Bean
ResultSetHandler<List<T>> resultSetHandler = new BeanListHandler<>(classInstance);
List<T> requiredList = resultSetHandler.handle(rs);
return requiredList;
}
}
我的示例主类如下所示:
public class MyMain {
public static void main() {
MyConnectionPool myConnectionPool = new MyConnectionPool();
Connection connection1 = myConnectionPool.getConnection();
Connection connection2 = myConnectionPool.getConnection();
String studentSql = "Select X, Y from AB.Students Where Z = 2";
String teacherSql = "Select P, Q from AB.Teachers Where R = 1";
ExecutorService executorService = Executors.newFixedThreadPool(6);
Callable<List<Student>> callableStudents = new MyCallableTask<>(studentSql, connection1, Student.class);
Callable<List<Teacher>> callableTeachers = new MyCallableTask<>(teacherSql, connection2, Teacher.class);
Future<List<Student>> studentsFuture = executorService.submit(callableStudents);
Future<List<Teacher>> teachersFuture = executorService.submit(callableTeachers);
List<Student> students = studentsFuture.get();
List<Teacher> teachers = teachersFuture.get();
System.out.println(students + " " + teachers);
}
}
上面的代码按预期适用于两个不同线程上的每个 sql 查询,但在我调用的行上失败
List<T> requiredList = resultSetHandler.handle(rs);
抛出的异常是 NoSuchElementException。这个案例对我来说很好奇,因为当我同步运行上述内容时,它工作得非常好。事实上,即使我插入断点并在调试模式下运行,它也运行得非常好,并按预期创建了两个不同的工作线程。但它总是在正常运行时中断。
如果可能,请尝试回答。非常感谢任何帮助。