How to Convert a Runnable into a Callable in Java

In Java there are two ways to implement a class whose instances are to be executed by a thread.

  1. By implementing Runnable interface.
  2. By implementing Callable interface.

Check this post Difference Between Runnable And Callable in Java to know the differences between Runnable and Callable in Java.

But what if you have a Runnable and you want to convert it into a Callable in Java at runtime. Executors class in Java provides utility methods to do that conversion.

  • callable(Runnable task)– Returns a Callable object that, when called, runs the given task and returns null.
  • callable(Runnable task, T result)– Returns a Callable object that, when called, runs the given task and returns the given result.

Converting Runnable to Callable in Java

1- Using the first method – callable(Runnable task)

public class RunnableToCallable {
  public static void main(String[] args) {
    ExecutorService es = Executors.newFixedThreadPool(2);
    // converting runnable task to callable
    Callable<Object> callable = Executors.callable(new MyRunnable());
    // submit method
    Future<Object> f = es.submit(callable);
    try {
      System.out.println("Result- " + f.get());
    } catch (InterruptedException | ExecutionException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    es.shutdown();
  }
}

class MyRunnable implements Runnable{
  @Override
  public void run() {
    System.out.println("Running task..");
  }
}

Output

Running task..
Result- null

2- Using the second method- callable(Runnable task, T result)

public class RunnableToCallable {
  public static void main(String[] args) {
    ExecutorService es = Executors.newFixedThreadPool(2);
    // converting runnable task to callable
    Callable<String> callable = Executors.callable(new MyRunnable(), "From callable");
    // submit method
    Future<String> f = es.submit(callable);
    try {
      System.out.println("Result- " + f.get());
    } catch (InterruptedException | ExecutionException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    es.shutdown();
  }
}

class MyRunnable implements Runnable{
  @Override
  public void run() {
    System.out.println("Running task..");
  }
}

Output

Running task..
Result- From callable

Related Posts

That’s all for the topic How to Convert a Runnable into a Callable in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.