Comparison of Runnable Callable Future and FutureTask in Java

  • 2020-06-12 08:58:33
  • OfStack

Comparison of Runnable, Callable, Future and FutureTask in Java

There are several thread-related classes or interfaces in Java, including Runnable, Callable, Future, and FutureTask, which are also important concepts in Java. Let's take a look at the following simple examples to see how they work differently.

Runnable

Runnable, which is probably the most familiar interface, has only one run() function, which is used to write time-consuming operations in it and does not return a value. Multithreading can then be achieved by using a thread to execute the runnable. The Thread class executes the run() function of Runnable after calling the start() function. Runnable's statement reads as follows:


@FunctionalInterface
public interface Runnable {
  /**
   * When an object implementing interface <code>Runnable</code> is used
   * to create a thread, starting the thread causes the object's
   * <code>run</code> method to be called in that separately executing
   * thread.
   * <p>
   * The general contract of the method <code>run</code> is that it may
   * take any action whatsoever.
   *
   * @see   java.lang.Thread#run()
   */
  public abstract void run();
}

Callable

Callable is roughly similar to Runnable in that there is one call() function in Callable, but the call() function has a return value, while the run() function of Runnable does not return the result to the client. Callable's statement reads as follows:


@FunctionalInterface
public interface Callable<V> {
  /**
   * Computes a result, or throws an exception if unable to do so.
   *
   * @return computed result
   * @throws Exception if unable to compute a result
   */
  V call() throws Exception;
}

As you can see, this is a generic interface, and the call() function returns the type of V passed in by the client.

Future

Executor is the scheduling container of Runnable and Callable, and Future is the operation of canceling, inquiring whether the execution result of specific Runnable or Callable task is completed, obtaining the result and setting the result. The get method blocks until the task returns the result (about Future). Future declares as follows:


* @see FutureTask
 * @see Executor
 * @since 1.5
 * @author Doug Lea
 * @param <V> The result type returned by this Future's {@code get} method
 */
public interface Future<V> {

  /**
   * Attempts to cancel execution of this task. This attempt will
   * fail if the task has already completed, has already been cancelled,
   * or could not be cancelled for some other reason. If successful,
   * and this task has not started when {@code cancel} is called,
   * this task should never run. If the task has already started,
   * then the {@code mayInterruptIfRunning} parameter determines
   * whether the thread executing this task should be interrupted in
   * an attempt to stop the task.
   *
   * <p>After this method returns, subsequent calls to {@link #isDone} will
   * always return {@code true}. Subsequent calls to {@link #isCancelled}
   * will always return {@code true} if this method returned {@code true}.
   *
   * @param mayInterruptIfRunning {@code true} if the thread executing this
   * task should be interrupted; otherwise, in-progress tasks are allowed
   * to complete
   * @return {@code false} if the task could not be cancelled,
   * typically because it has already completed normally;
   * {@code true} otherwise
   */
  boolean cancel(boolean mayInterruptIfRunning);

  /**
   * Returns {@code true} if this task was cancelled before it completed
   * normally.
   *
   * @return {@code true} if this task was cancelled before it completed
   */
  boolean isCancelled();

  /**
   * Returns {@code true} if this task completed.
   *
   * Completion may be due to normal termination, an exception, or
   * cancellation -- in all of these cases, this method will return
   * {@code true}.
   *
   * @return {@code true} if this task completed
   */
  boolean isDone();

  /**
   * Waits if necessary for the computation to complete, and then
   * retrieves its result.
   *
   * @return the computed result
   * @throws CancellationException if the computation was cancelled
   * @throws ExecutionException if the computation threw an
   * exception
   * @throws InterruptedException if the current thread was interrupted
   * while waiting
   */
  V get() throws InterruptedException, ExecutionException;

  /**
   * Waits if necessary for at most the given time for the computation
   * to complete, and then retrieves its result, if available.
   *
   * @param timeout the maximum time to wait
   * @param unit the time unit of the timeout argument
   * @return the computed result
   * @throws CancellationException if the computation was cancelled
   * @throws ExecutionException if the computation threw an
   * exception
   * @throws InterruptedException if the current thread was interrupted
   * while waiting
   * @throws TimeoutException if the wait timed out
   */
  V get(long timeout, TimeUnit unit)
    throws InterruptedException, ExecutionException, TimeoutException;
}

FutureTask

FutureTask is one RunnableFuture < V > RunnableFuture implemented Runnbale and Futrue < V > These two interfaces:


public class FutureTask<V> implements RunnableFuture<V> {
......
}

RunnableFuture



/**
 * A {@link Future} that is {@link Runnable}. Successful execution of
 * the {@code run} method causes completion of the {@code Future}
 * and allows access to its results.
 * @see FutureTask
 * @see Executor
 * @since 1.6
 * @author Doug Lea
 * @param <V> The result type returned by this Future's {@code get} method
 */
public interface RunnableFuture<V> extends Runnable, Future<V> {
  /**
   * Sets this Future to the result of its computation
   * unless it has been cancelled.
   */
  void run();
}

In addition, FutureTask can be packaged as Runnable and Callable < V > , injected by the constructor.


/**
   * Creates a {@code FutureTask} that will, upon running, execute the
   * given {@code Callable}.
   *
   * @param callable the callable task
   * @throws NullPointerException if the callable is null
   */
  public FutureTask(Callable<V> callable) {
    if (callable == null)
      throw new NullPointerException();
    this.callable = callable;
    this.state = NEW;    // ensure visibility of callable
  }

  /**
   * Creates a {@code FutureTask} that will, upon running, execute the
   * given {@code Runnable}, and arrange that {@code get} will return the
   * given result on successful completion.
   *
   * @param runnable the runnable task
   * @param result the result to return on successful completion. If
   * you don't need a particular result, consider using
   * constructions of the form:
   * {@code Future<?> f = new FutureTask<Void>(runnable, null)}
   * @throws NullPointerException if the runnable is null
   */
  public FutureTask(Runnable runnable, V result) {
    this.callable = Executors.callable(runnable, result);
    this.state = NEW;    // ensure visibility of callable
  }

As you can see, the Runnable injection is converted to the Callable type by the Executors.callable () function, that is, FutureTask ultimately performs tasks of the Callable type. The implementation of the adaptation function is as follows:


/**
   * Returns a {@link Callable} object that, when
   * called, runs the given task and returns the given result. This
   * can be useful when applying methods requiring a
   * {@code Callable} to an otherwise resultless action.
   * @param task the task to run
   * @param result the result to return
   * @param <T> the type of the result
   * @return a callable object
   * @throws NullPointerException if task null
   */
  public static <T> Callable<T> callable(Runnable task, T result) {
    if (task == null)
      throw new NullPointerException();
    return new RunnableAdapter<T>(task, result);
  }

RunnableAdapter adapter


/**
   * A callable that runs given task and returns given result
   */
  static final class RunnableAdapter<T> implements Callable<T> {
    final Runnable task;
    final T result;
    RunnableAdapter(Runnable task, T result) {
      this.task = task;
      this.result = result;
    }
    public T call() {
      task.run();
      return result;
    }
  }

Since FutureTask implements Runnable, it can be executed either directly through the Thread wrapper or submitted to ExecuteService for execution. You can also get the result of the execution directly through the get() function, which blocks until the result is returned.

So FutureTask is both Future and Runnable, as well as packaging Callable(which will eventually be converted to Callable if it is Runnable), it is a combination of both.

Complete example:


package com.stay4it.rx;

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.FutureTask;

public class FutureTest {

  public static class Task implements Runnable {

    @Override
    public void run() {
      // TODO Auto-generated method stub
      System.out.println("run");
    }

  }
  public static class Task2 implements Callable<Integer> {

    @Override
    public Integer call() throws Exception {
      System.out.println("call");
      return fibc(30);
    }

  }

   /** 
   * runnable,  There is no return value  
   */ 
  public static void testRunnable(){
    ExecutorService executorService = Executors.newCachedThreadPool();

    Future<String> future = (Future<String>) executorService.submit(new Task());
    try {
      System.out.println(future.get());
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (ExecutionException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    executorService.shutdown();
  }

  /** 
   * Callable,  Returns a value  
   */ 
  public static void testCallable(){
    ExecutorService executorService = Executors.newCachedThreadPool();

    Future<Integer> future = (Future<Integer>) executorService.submit(new Task2());
    try {
      System.out.println(future.get());
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (ExecutionException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    executorService.shutdown();
  }

   /** 
   * FutureTask It is 1 a RunnableFuture<V> ", that's it Runnbale And to achieve the Futrue<V> These two interfaces,  
   *  It can also be packaged Runnable( It's actually going to convert to theta Callable) and Callable 
   * <V> , so 1 As it is 1 It's a coincidence body. It can pass Thread Packaging can be executed directly or submitted to ExecuteService To perform the  
   *  And it's still passable v get() Returns the execution result of the main thread when the body of the thread has not finished executing 1 Block and wait, and then return the result.  
   */ 
  public static void testFutureTask(){
    ExecutorService executorService = Executors.newCachedThreadPool();
    FutureTask<Integer> futureTask = new FutureTask<Integer>(new Task2());

    executorService.submit(futureTask);
    try {
      System.out.println(futureTask.get());
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (ExecutionException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    executorService.shutdown();
  }

   /** 
   * FutureTask It is 1 a RunnableFuture<V> ", that's it Runnbale And to achieve the Futrue<V> These two interfaces,  
   *  It can also be packaged Runnable( It's actually going to convert to theta Callable) and Callable 
   * <V> , so 1 As it is 1 It's a coincidence body. It can pass Thread Packaging can be executed directly or submitted to ExecuteService To perform the  
   *  And it's still passable v get() Returns the execution result of the main thread when the body of the thread has not finished executing 1 Block and wait, and then return the result.  
   */ 
  public static void testFutureTask2(){
    ExecutorService executorService = Executors.newCachedThreadPool();
    FutureTask<Integer> futureTask = new FutureTask<Integer>(new Runnable() {

      @Override
      public void run() {
        // TODO Auto-generated method stub
        System.out.println("testFutureTask2 run");
      }
    },fibc(30));

    executorService.submit(futureTask);
    try {
      System.out.println(futureTask.get());
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (ExecutionException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    executorService.shutdown();
  }



  public static void main(String[] args) {

    testCallable();

  }

  /** 
   *  An inefficient Fibonacci sequence ,  Time-consuming operation  
   * 
   * @param num 
   * @return 
   */ 
  static int fibc(int num) { 
    if (num == 0) { 
      return 0; 
    } 
    if (num == 1) { 
      return 1; 
    } 
    return fibc(num - 1) + fibc(num - 2); 
  } 

}

Thank you for reading, I hope to help you, thank you for your support to this site!


Related articles: