Reputation: 25032
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?
Upvotes: 1
Views: 1840
Reputation: 17854
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();
Upvotes: 1