StackStalk
  • Home
  • Java
    • Java Collection
    • Spring Boot Collection
  • Python
    • Python Collection
  • C++
    • C++ Collection
    • Progamming Problems
    • Algorithms
    • Data Structures
    • Design Patterns
  • General
    • Tips and Tricks

Saturday, September 6, 2014

Java Callable Future

 September 06, 2014     Java     No comments   

Java Callable Future Introduction

Java concurrent API support Callable and Future interfaces to implement threads that can return a value. One simple use case for a Callable object is to return status (Success/ Failure) of thread execution to the invoking object. More practical use cases include perform number crunching operations simultaneously wherein partial results could be return back to the parent object. This article provides a quick introduction to Callable and Future interfaces with an example.

The Callable interface is similar to Runnable, in that both are designed for classes whose instances are potentially executed by another thread. Main difference is that Runnable object cannot return a value whereas a Callable can return.

Future interface is the value returned by a Callable object. We need a ExecutorService object to execute a Callable task. Refer to this link for more information on ExecutorService. The submit() method on the executor object is used to execute the Callable tasks.

To read the return value from Future object get() API can be used. There are 2 flavors of get() API.

  • get() - Waits if necessary for the computation to complete, and then retrieves its result.
  • get(long timeout, TimeUnit) - Waits if necessary for at most the given time for the computation to complete, and then retrieves its result, if available.

Java Callable Future Example

In this example we create a Callable task SumToN and we execute the task using an ExecutorService. Return value is captured using the Future object.
package com.sourcetricks.callable;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CallableDemo {
  
  private static class SumToN implements Callable<Integer> {

    private int n;
    
    public SumToN(int n) {
      this.n = n;
    }
    
    @Override
    public Integer call() throws Exception {
      int sum = 0;
      for ( int i = 0; i < n; i++ ) {
        sum += i;
      }
      return sum;
    }
    
  }

  public static void main(String[] args) {
    ExecutorService executor = Executors.newFixedThreadPool(2);
    Future<Integer> futureVal1 = executor.submit(new SumToN(100));
    Future<Integer> futureVal2 = executor.submit(new SumToN(1000));
    try {
      System.out.println(futureVal1.get());
      System.out.println(futureVal2.get(2000, TimeUnit.MILLISECONDS));
    } catch (InterruptedException | ExecutionException | TimeoutException e) {
      e.printStackTrace();
    }
  }
}
This program produces the following output.
4950
499500
Read other concurrency tutorials from Java Tutorials page.
  • Share This:  
Newer Post Older Post Home

0 comments:

Post a Comment

Follow @StackStalk
Get new posts by email:
Powered by follow.it

Popular Posts

  • Avro Producer and Consumer with Python using Confluent Kafka
    In this article, we will understand Avro a popular data serialization format in streaming data applications and develop a simple Avro Produc...
  • Monitor Spring Boot App with Micrometer and Prometheus
    Modern distributed applications typically have multiple microservices working together. Ability to monitor and manage aspects like health, m...
  • Server-Sent Events with Spring WebFlux
    In this article we will review the concepts of server-sent events and work on an example using WebFlux. Before getting into this article it ...
  • Implement caching in a Spring Boot microservice using Redis
    In this article we will explore how to use Redis as a data cache for a Spring Boot microservice using PostgreSQL as the database. Idea is to...
  • Python FastAPI microservice with Okta and OPA
    Authentication (AuthN) and Authorization (AuthZ) is a common challenge when developing microservices. In this article, we will explore how t...
  • Spring Boot with Okta and OPA
    Authentication (AuthN) and Authorization (AuthZ) is a common challenge when developing microservices. In this article, we will explore how t...
  • Getting started with Kafka in Python
    This article will provide an overview of Kafka and how to get started with Kafka in Python with a simple example. What is Kafka? ...
  • Getting started in GraphQL with Spring Boot
    In this article we will explore basic concepts on GraphQL and look at how to develop a microservice in Spring Boot with GraphQL support. ...

Copyright © StackStalk