如何解决多线程并行查询中的ResultSetHandler问题
我正在尝试从Java应用程序在Oracle数据库中并行进行多个读取查询。我使用CallableTasks进行这些查询。可调用任务的示例如下:
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。这种情况对我来说很好奇,因为当我同步运行上面的代码时,它工作得很好。即使我插入断点并在调试模式下运行,它实际上仍然运行良好,并且可以按预期创建两个不同的工作线程。但是它总是会在正常运行中中断。
如果可能,请尝试回答。非常感谢您的帮助。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。