Ticker

6/recent/ticker-posts

Ad Code

Responsive Advertisement

Java FutureTask example with Callable and Runnable

Java FutureTask example with Callable and Runnable

Let’s get started on Java FutureTask example.

This class provides a base implementation of Future, with methods to start and cancel a computation, query to see if the computation is complete, and retrieve the result of the computation.

If you have any of below questions then you are at right place:

  • Java FutureTask Example Program
  • Future and FutureTask in java
  • How to use Future and FutureTask in Java Concurrency
  • java.util.concurrent.FutureTask Example

The result can only be retrieved when the computation has completed; the get methods will block if the computation has not yet completed.

Once the computation has completed, the computation cannot be restarted or cancelled (unless the computation is invoked using runAndReset()).

FutureTask can be used to wrap a Callable or Runnable object. Because FutureTask implements Runnable, a FutureTask can be submitted to an Executor for execution.

In addition to serving as a standalone class, this class provides protected functionality that may be useful when creating customized task classes.

Here is a simple Java Example in which we will create two classes: CrunchifyCallable.java and CrunchifyFutureTask.java.

Another must read:

Create Class CrunchifyFutureTask.java


ExecutorService:

  • An Executor that provides methods to manage termination and methods that can produce a Future for tracking progress of one or more asynchronous tasks.
  • An ExecutorService can be shut down, which will cause it to reject new tasks. Two different methods are provided for shutting down an ExecutorService.
  • The shutdown method will allow previously submitted tasks to execute before terminating, while the shutdownNow method prevents waiting tasks from starting and attempts to stop currently executing tasks.
  • Upon termination, an executor has no tasks actively executing, no tasks awaiting execution, and no new tasks can be submitted. An unused ExecutorService should be shut down to allow reclamation of its resources.

shutdown():

  • Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted.
  • Invocation has no additional effect if already shut down.

Here is a code:

package crunchify.com.tutorials;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * @author Crunchify.com
 * Java FutureTask example with Callable and Runnable.
 */

public class CrunchifyFutureTask {

    public static void main(String[] args) {
        CrunchifyCallable crunchifyCallable1 = new CrunchifyCallable(2000);
        CrunchifyCallable crunchifyCallable2 = new CrunchifyCallable(4000);

                // FutureTask: Creates a FutureTask that will, upon running, execute the given Callable.
        FutureTask<String> futureTask1 = new FutureTask<String>(
                crunchifyCallable1);
        FutureTask<String> futureTask2 = new FutureTask<String>(
                crunchifyCallable2);

                // Creates a thread pool that reuses a fixed number of threads operating
        // off a shared unbounded queue. At any point, at most nThreads threads
        // will be active processing tasks.

                // An Executor that provides methods to manage termination and methods that can produce a Future for tracking progress of one or more asynchronous tasks.
                // An ExecutorService can be shut down, which will cause it to reject new tasks. Two different methods are provided for shutting down an ExecutorService.
                // The shutdown method will allow previously submitted tasks to execute before terminating,
                // while the shutdownNow method prevents waiting tasks from starting and attempts to stop currently executing tasks.
                // Upon termination, an executor has no tasks actively executing, no tasks awaiting execution, and no new tasks can be submitted.
                // An unused ExecutorService should be shut down to allow reclamation of its resources.
        ExecutorService crunchifyExecutor = Executors.newFixedThreadPool(2);
                crunchifyExecutor.execute(futureTask1);
                crunchifyExecutor.execute(futureTask2);

        while (true) {
            try {
                if (futureTask1.isDone() && futureTask2.isDone()) {
                    System.out.println("Done");
                    // Initiates an orderly shutdown in which previously
                    // submitted tasks are executed, but no new tasks will be
                    // accepted. Invocation has no additional effect if already
                    // shut down.
                                        crunchifyExecutor.shutdown();
                    return;
                }

                if (!futureTask2.isDone()) {
                    // wait indefinitely for future task to complete
                    System.out.println("FutureTask1 output="
                            + futureTask1.get());
                }

                System.out.println("Waiting for FutureTask1 to complete");
                String crunchifyString = futureTask2.get(200L, TimeUnit.MILLISECONDS);
                if (crunchifyString != null) {
                    System.out.println("FutureTask1 output=" + crunchifyString);
                }

                                // InterruptedException: Thrown when a thread is waiting, sleeping, or otherwise occupied,
                                // and the thread is interrupted, either before or during the activity.
                                // Occasionally a method may wish to test whether the current thread has been interrupted, and if so, to immediately throw this exception.
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();

                                // TimeoutException: Exception thrown when a blocking operation times out.
                                // Blocking operations for which a timeout is specified need a means to indicate that the timeout has occurred.
                                // For many such operations it is possible to return a value that indicates timeout;
                                // when that is not possible or desirable then TimeoutException should be declared and thrown.
            } catch (TimeoutException e) {
                // exception
            }

                        // ExcutionException: Exception thrown when attempting to retrieve the result of a task that aborted by throwing an exception.
                        // This exception can be inspected using the getCause() method.
        }
    }
}

IntelliJ IDEA Console Result:

FutureTask1 output=pool-1-thread-1
Waiting for FutureTask1 to complete
FutureTask1 output=pool-1-thread-1
Waiting for FutureTask1 to complete
FutureTask1 output=pool-1-thread-1
Waiting for FutureTask1 to complete
FutureTask1 output=pool-1-thread-1
Waiting for FutureTask1 to complete
FutureTask1 output=pool-1-thread-1
Waiting for FutureTask1 to complete
FutureTask1 output=pool-1-thread-1
Waiting for FutureTask1 to complete
FutureTask1 output=pool-1-thread-1
Waiting for FutureTask1 to complete
FutureTask1 output=pool-1-thread-1
Waiting for FutureTask1 to complete
FutureTask1 output=pool-1-thread-1
Waiting for FutureTask1 to complete
FutureTask1 output=pool-1-thread-1
Waiting for FutureTask1 to complete
FutureTask1 output=pool-1-thread-2
Done

Process finished with exit code 0

The post Java FutureTask example with Callable and Runnable appeared first on Crunchify.

Enregistrer un commentaire

0 Commentaires