I am developing an API. This API needs to do 2 DB queries to get the result.
I tried following strategies:
- Used callable as return type in Controller.
Created 2 threads in Service (use Callable and CoundownLatch) to run 2 queries parallel and detect finishing time.
public class PetService { public Object getData() { CountDownLatch latch = new CountDownLatch(2); AsyncQueryDBTask<Integer> firstQuery= new AsyncQueryDBTask<>(latch); AsyncQueryDBTask<Integer> secondQuery= new AsyncQueryDBTask<>(latch); latch.await(); } public class AsyncQueryDBTask<T> implements Callable { private CountDownLatch latch; public AsyncQueryDBTask(CountDownLatch latch) { this.latch = latch;} @Override public T call() throws Exception { //Run query latch.countDown(); }
It worked fine but I feel that I am breaking the structure of Spring somewhere.
I wonder what is the most efficient way to get data in Spring 4.
-How to know both of 2 threads that run own query completed their job?
-How to control thread resource such as use and release thread?
Thanks in advance.