Java Language Executor, ExecutorService and Thread pools Retrieving value from computation - Callable

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

If your computation produces some return value which later is required, a simple Runnable task isn't sufficient. For such cases you can use ExecutorService.submit(Callable<T>) which returns a value after execution completes.

The Service will return a Future which you can use to retrieve the result of the task execution.

// Submit a callable for execution
ExecutorService pool = anExecutorService;
Future<Integer> future = pool.submit(new Callable<Integer>() {
    @Override public Integer call() {
        //do some computation
        return new Random().nextInt();
    }
});    
// ... perform other tasks while future is executed in a different thread

When you need to get the result of the future, call future.get()

  • Wait indefinitely for future to finish with a result.

      try {
          // Blocks current thread until future is completed
          Integer result = future.get(); 
      catch (InterruptedException || ExecutionException e) {
          // handle appropriately
      }
    
  • Wait for future to finish, but no longer than specified time.

      try {
          // Blocks current thread for a maximum of 500 milliseconds.
          // If the future finishes before that, result is returned,
          // otherwise TimeoutException is thrown.
          Integer result = future.get(500, TimeUnit.MILLISECONDS); 
      catch (InterruptedException || ExecutionException || TimeoutException e) {
          // handle appropriately
      }
    

If the result of a scheduled or running task is no longer required, you can call Future.cancel(boolean) to cancel it.

  • Calling cancel(false) will just remove the task from the queue of tasks to be run.
  • Calling cancel(true) will also interrupt the task if it is currently running.


Got any Java Language Question?