[Threading - Java] Future and FutureTask


1) Overview


  • Future interface provides method to check if computation is complete, wait for completion and retrieve the results of the computation. 
  • The result is retrieved using Future's get() method if computation is completed. If it is not, then it blocks until it is completed.
  • FutureTask is an implementation of Future interface and RunnableFuture Interface - you can use FutureTask as Runnable to be submitted to ExecutorService.

2) Example

Create two task. After one is completely executed, then after waiting 2000ms, second task starts.



Output

FutureTask1 output=FutureTask1 is complete
Waiting for FutureTask2 to complete
Waiting for FutureTask2 to complete
Waiting for FutureTask2 to complete
Waiting for FutureTask2 to complete
FutureTask2 output=FutureTask2 is complete
Both FutureTask Complete

Resource

Comments

Popular posts from this blog

[Redis] Redis Cluster vs Redis Sentinel

[Unit Testing] Test Doubles (Stubs, Mocks....etc)

[Node.js] Pending HTTP requests lead to unresponsive nodeJS