简体   繁体   中英

How do I run multiple queries in parallel in java?

I have a bean that is getting a lot of information to show on a page. Each bit of this information is obtained by hitting the db and currently this is happening sequentially. Here is some sample code from my bean :

int transactionCount = dao.getTransactionCount();
int personCount = dao.getPersonCount();
int carCount = dao.getCarCount();
int houseCount = dao.getHouseCount();

I am running Java 7 . How could I run this in parallel? I have looked at the ExecutorService and ForkJoin , but both seem to have to run the same exact code over and over again. That is not what I am doing here. What is the best way to speed this up?

Of course you can submit different tasks to a single Executor. You just need to keep the Futures separated to get each task's result:

static ExecutorService executor = Executors.newFixedThreadPool(NTHREDS);

//start threads
Future<Integer> transactionCountFuture = executor.submit(()-> dao.getTransactionCount());
Future<Integer> personCountFuture = executor.submit(()-> dao.getPersonCount());
Future<Integer> carCountFuture = executor.submit(()-> dao.getCarCount());
Future<Integer> houseCountFuture = executor.submit(()-> dao.getHouseCount());

//wait until all calls returns a result
int transactionCount = transactionCountFuture.get();
int personCount = personCountFuture.get();
int carCountCount = carCountFuture.get();
int houseCount = houseCountFuture.get();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM