Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the get method in Future works in java?

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?

like image 632
Vijay Ram Avatar asked Oct 19 '25 01:10

Vijay Ram


1 Answers

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:

  1. Throw an exception if the Future was cancelled, or if the underlying task generated an exception
  2. 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.

like image 117
Perception Avatar answered Oct 22 '25 07:10

Perception



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!