Friday, June 14, 2019

Callable Interface Example

public interface Callable<V>

Type Parameters:
V - the result type of method call

All Known Subinterfaces:

It is a part of concurrent collections framework since java 1.5 and is present in java.util.concurrent package.
The Callable interface is like to Runnable, But callable returns a result as Future object and may throw an exception. and both are designed for classes whose instances are potentially executed by another thread.
A Runnable does not return a result and cannot throw a checked exception.

Callable interface: Callable interface was added in Java 5 to complement existing Runnable interface, which is used to wrap a task and pass it to a Thread or thread pool for asynchronous execution.
The Callable interface is designed to define a task that returns a result as Future object and may throw an exception. It is declared in the java.util.concurrent package. This interface also contains a single, no-argument method, called call (), to be overridden by the implementors of this interface.

Future interface: Java Future provides following method, associated with Callable task.
  • public boolean cancel(boolean mayInterrupt): cancel() methods is used to stop the runing task. It stops the task if it has not started. If it has started, it interrupts the task only if mayInterrupt is true.
  • public Object get() throws InterruptedException, ExecutionException: get() mthods is used to get the result of the task. If the task is complete, it returns the result immediately, otherwise it waits till the task is complete and then returns the result.
  • public boolean isDone(): Returns true if the task is complete and false otherwise

  Note:-   get() method of Future, which will return result of computation or block if Computation is not complete. If you don't like indefinite blocking then you can also use overloaded get() method with timeout.  

package com.shubh.example;

import java.util.concurrent.Callable;

public class MyCallable implements Callable
 private int number;
    private Message message;
    public MyCallable(Message message, int number) {
        this.message = message;
        this.number = number;
    public Message call() throws Exception {
     message.setMessage("Message Number - "+number);
        System.out.println("Result messageId: "+ number);
        return message;

package com.shubh.example;

public class Message {

 int messageId;
 String message;

 public int getMessageId() {
  return messageId;

 public void setMessageId(int messageId) {
  this.messageId = messageId;

 public String getMessage() {
  return message;

 public void setMessage(String message) {
  this.message = message;

package com.shubh.example;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;

public class CallableExample {
 public static void main(String[] args) {
  ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(2);

  List> resultList = new ArrayList<>();

  Random random = new Random();

  for (int i = 0; i < 4; i++) {
   Message message = new Message();
   int number = random.nextInt(10);
   MyCallable printMessage = new MyCallable(message, number);
   Future result = executor.submit(printMessage);

  for (Future future : resultList) {
   try {
    Message resMessage = future.get();
    System.out.println("Future result : Message Id :" + resMessage.getMessageId() + " Message :"
      + resMessage.getMessage() + "; And Task done is " + future.isDone());
   } catch (InterruptedException | ExecutionException e) {
  // shut down the executor service now

No comments:

Post a Comment