Note that there are some explanatory texts on larger screens.

plurals
  1. POHow does Java Future multithreading return result ?
    primarykey
    data
    text
    <p>I am still learning about using Future and Callable in Java. Stumble into this question:</p> <p>Say I have class:</p> <pre><code>TaskWorker implements Callable { public String id; public TaskWorker(String id) { this.id = id; } public Documents call() trows Exception { //Assume here, that Search and Doc are my own method to search and retrieve docs Search search = new Search(); Documents docResult = search.process(id); //think about documents has getDocs //docResult.getDocs() will return number of document found from search return docResult; } } </code></pre> <p>And here is the main method:</p> <pre><code>public static void main(String[] args) { //assume here, that I build in request contains many Id Request request = new Request(); request.process; ExecutorService service = Executors.newFixedThreadPool(3); List&lt;Future&lt;Documents&gt;&gt; result = new ArrayList&lt;Future&lt;Documents&gt;&gt;(); for (int i=0;i&lt;request.length;i++) { Callable&lt;Documents&gt; worker = new TaskWorker(request.getId[i]); Future&lt;Documents&gt; submit = executor.submit(worker); result.add(submit); } Response response = new Response(); ArrayList&lt;Documents&gt; docList = new ArrayList&lt;Documents&gt;(); for (Future&lt;Documents&gt; future:result) { docList.add(future.get().getDocs()); } response.setDocuments(docList); } </code></pre> <p>What I am trying to do is, breaking a part the request to run in separate thread since each of the request Id is separate Search process. So I am trying to utilize Java pooling, by storing the result in the future object.</p> <p>The thing I am confused is, how does future will work in this case? For each thread completion, is it going to hold the results? And after all the process finish, I can just loop future object to get the results right?</p> <p>Also, there is no guarantee that process will run in order (1,2,3,4,etc), right? If that the case, then what is the best strategy if I want to associate each original request with the future result?</p> <p>Please advise.</p> <p>Thanks</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload