I have three queries to run all are like "select * from table" they are taking so much time.
I want to run all query in parallel using java concurrency, how I achieve this.
1 Answer
You can wrap your db calls in a Callable like this:
public class SqlTask implements Callable<ResultSet> {
private String sql;
public SqlTask(final String sql) {
this.sql = sql;
}
@Override
public ResultSet call() throws Exception {
Connection connection = ...; // get connection
Statement stmt = connection.createStatement();
return stmt.executeQuery(this.sql);
}
}
and then execute them in parralel using an ExecutorService, for example:
final ExecutorService executor = Executors.newCachedThreadPool();
final Future<ResultSet> futureResult1 = executor.submit (new SqlTask("SELECT * FROM table1"));
final Future<ResultSet> futureResult2 = executor.submit(new SqlTask("SELECT * FROM table2"));
final Future<ResultSet> futureResult3 = executor.submit(new SqlTask("SELECT * FROM table3"));
final ResultSet result1 = futureResult1.get();
final ResultSet result2 = futureResult2.get();
final ResultSet result3 = futureResult3.get();
2 Comments
user3543851
thank you..and how I get three resultset back? I mean how I refer that three resultset?
Fradenger
Ok, I have added that. Future is a container for some asynchronous results. Then you call get() on it to get the real result (this call might block until the query returns)
Callableand have query execution ascall()method body, executor with 3 threads, submit these tasks (you'll get backFutures) and get results.