0

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.

2
  • What type of database are you working with? Commented Jun 11, 2014 at 13:14
  • Create 3 task classes which implement Callable and have query execution as call() method body, executor with 3 threads, submit these tasks (you'll get back Futures) and get results. Commented Jun 11, 2014 at 13:21

1 Answer 1

2

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();
Sign up to request clarification or add additional context in comments.

2 Comments

thank you..and how I get three resultset back? I mean how I refer that three resultset?
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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.