The Future is a framework in the Java Concurrent API that represents the result of an asynchronous computation. A Future provides methods to check the status of a task, to wait for its completion, and to retrieve its result.
Here is a simple example that demonstrates how to use the Future:
import java.util.concurrent.*;
public class FutureExample {
public static void main(String[] args) throws ExecutionException, InterruptedException {
// Create a fixed thread pool with one thread
ExecutorService executorService = Executors.newFixedThreadPool(1);
// Submit a task to the executor service and get the future
Future<Integer> future = executorService.submit(() -> {
System.out.println("Running task");
TimeUnit.SECONDS.sleep(2);
return 42;
});
// Check if the task is done
while (!future.isDone()) {
System.out.println("Task is not done yet");
TimeUnit.MILLISECONDS.sleep(100);
}
// Get the result of the task
System.out.println("Task is done. Result: " + future.get());
// Shut down the executor service
executorService.shutdown();
}
}
In this example, we create a fixed thread pool with one thread using the newFixedThreadPool method of the Executors class. We then submit a task to the executor service using the submit method and get the future of the task.
We use the isDone method of the Future to check if the task is done, and we use the get method to retrieve the result of the task.
The output of this program is:
Running task
Task is not done yet
Task is not done yet
Task is done. Result: 42
Note that the get method blocks until the task is complete. This means that the get method should not be called from within a task that is being executed by the same executor service, as this would result in a deadlock.
The Future is an essential component of the Java Concurrent API, and it is used extensively to manage the execution of tasks and the retrieval of results.
cancel: The cancel method is used to cancel the execution of a task. The cancel method returns a boolean value indicating whether the task was successfully cancelled.isCancelled: The isCancelled method is used to check if a task has been cancelled.get(long timeout, TimeUnit unit): The get method with a timeout argument is used to wait for the completion of a task for a specified amount of time. If the task does not complete within the specified time, a TimeoutException is thrown.isDone: The isDone method is used to check if a task has completed.getNow: The getNow method is used to retrieve the result of a task without waiting for its completion. If the task is not yet complete, the getNow method returns a specified default value.complete: The complete method is used to complete a Future with a specified result or exception. This method can be used to create custom Futures that are completed manually.
Here is an example of how to use the cancel method:
import java.util.concurrent.*;
public class FutureCancelExample {
public static void main(String[] args) throws ExecutionException, InterruptedException {
// Create a fixed thread pool with one thread
ExecutorService executorService = Executors.newFixedThreadPool(1);
// Submit a task to the executor service and get the future
Future<Integer> future = executorService.submit(() -> {
System.out.println("Running task");
TimeUnit.SECONDS.sleep(2);
return 42;
});
// Cancel the task
System.out.println("Cancelling task: " + future.cancel(true));
// Check if the task is done
System.out.println("Task is done: " + future.isDone());
// Check if the task is cancelled
System.out.println("Task is cancelled: " + future.isCancelled());
// Shut down the executor service
executorService.shutdown();
}
}
The output of this program is:
Running task
Cancelling task: true
Task is done: false
Task is cancelled: true
In this example, we submit a task to the executor service as before, and then we use the cancel method to cancel the task. We use the isDone and isCancelled methods to check the status of the task.
Note that the cancel method does not guarantee that the task will be cancelled. The task may still complete if it is already running or if it has already completed. The isCancelled method can be used to check if the task was successfully cancelled.
No comments:
Post a Comment