How does the get method in Future works in java?
concurrency, java, multithreading
Solution
Your submitted task (in this case the Callable) is wrapped into the instance of the returned `Future`. In essence, the `Future` is directly related to the task it was created for, and not any other task.
Internally, when calling `get`, the future will attempt to acquire a lock that it shares in common with its wrapped task. Once acquired, it then queries the status of the task in order to determine what to do next:
- Throw an exception if the `Future` was cancelled, or if the underlying task generated an exception
- Otherwise, return the result that was generated by the task.
This is broadly how it works, there are several implementations of `Future` and they all have different internal logic.
Problem
Below is the piece of code that submits a job.. Let's say I have 3 threads running. how does the get method wait and obtain the appropriate thread results. ``` Future<?> result = threadPool.submitTasks(new Callable<T>() { public T call() throws Exception { // do something } }); anyType = (T) result.get(); ``` Or Lets say I have Task A resulted 1 and Task B resulted 2.. When it comes to get method, what is the guarantee that it returns the correct values?