Java parallel db calls -


i've web application needs extremely fast. processing requires access multiple data sources. therefore decided might useful make parallel calls optimization.

basically want make many different db calls in parallel. please recommend me simple , reliable way , technologies achieving goal, useful if provide few frameworks , design patterns.

right using spring.

you can use new java 8 completablefuture. allows use asynchronously existing synchronous method.

say have list of requests in form list<dbrequest> listrequest want run in parallel. can make stream , launching requests asynchronously in following way.

list<completablefuture<dbresult>> listfutureresult =                      listrequest.stream()                                 .map(req -> completablefuture.supplyasync(                                               () -> dblaunchrequest(req), executor))                                 .collect(collectors.tolist());     list<dbresult> listresult =                       listfutureresult.stream()                                      .map(completablefuture::join)                                      .collect(collectors.tolist()); 

to effective have write own custom executor

private final executor executor =      executors.newfixedthreadpool(math.min(listrequest.size(), 100),                                  new threadfactory(){                public thread newthread(runnable r){                     thread t = new thread(r);                     t.setdaemon(true);                     return t;                } }); 

like can have enough threads not much. marking threads deamons allows finish program if 1 thread blocked.

you can find clear explanations these techniques in chapter 11 of book java 8 in action

== update java 7 ==

if stick java 7, can use following solution:

class dbresult{} class dbrequest implements callable<dbresult>{     @override     public dbresult call(){return new dbresult();} } class asynctest{    public void test(){      try {          for(future<dbresult> futureresult : ((executorservice)executor).invokeall(listrequest)){              futureresult.get();          }      } catch (interruptedexception | executionexception ex) {          logger.getlogger(sotest.class.getname()).log(level.severe, null, ex);      }    } } 

all requests run asynchronously , wait completion, in order of list.

finally, answer subsidiary question in comment, don't have create thread pool each request.


Comments

Popular posts from this blog

javascript - AngularJS custom datepicker directive -

javascript - jQuery date picker - Disable dates after the selection from the first date picker -