If we call get method on FutureTask object, it is blocking call and returns once the computation is done.
Let’s understand more with the example.
Java FutureTask example:
Waitng for futureTask2 for completion
FutureTask2 output=800
Completed both the future task, shutting down the executors
Explanation:
- Create two callable task named multiplyingTask1 and multiplyingTask2. Please note that we have given sleep time as 2000 for multiplyingTask1 and 4000 for multiplyingTask2 so multiplyingTask2 will take more time than multiplyingTask1.
- Created two FutureTask objects named futureTask1 and futureTask2 by passing multiplyingTask1 and multiplyingTask2 respectively.
- Put an infinite loop condition with while(true)
- !futureTask1.isDone() checks for completion of futureTask1, if not done yet, we have called futureTask1.get(), as get method is blocking operation, current thread will wait for futureTask1 to complete.
- Once futureTask1 is done, we check !futureTask2.isDone() and above step is repeated for futureTask2.
- Once both the task i.e. futureTask1 and futureTask2 are done, we call shutdown() method on executors and return from it.