Java FutureTask Methods Explained
Common methods of FutureTask include:
- get(): obtain the result of a task, and if the task is not yet completed, wait until it is finished before returning the result.
- Retrieve the result of the task, waiting a specified amount of time determined by the timeout and unit parameters. If the task completes within the specified time, return the result; otherwise, throw a TimeoutException.
- cancel(boolean mayInterruptIfRunning): Attempt to cancel the execution of a task. If the task has already been completed or canceled, this method returns false; if the task has not yet started, it will attempt to cancel the execution of the task and return true; if the task is currently running and the mayInterruptIfRunning parameter is true, it will interrupt the execution of the task and return true; if the task is currently running and the mayInterruptIfRunning parameter is false, it is unable to cancel the execution of the task and returns false.
- isCancellationRequested(): Determine if the task has been cancelled.
- isDone(): check if the task has been completed.
- run(): Execute the task. This method is called when the task has not been executed yet.
- runAndReset(): Execute the task and reset its status. This method is called before the task is executed and resets the task’s status after completion, allowing it to be run again.
- set the result of the task and mark it as completed.
- setException(Throwable throwable): Set the exception thrown during task execution and mark the task as complete.
- isPeriodic() checks if the task is a periodic task. This method is not specifically implemented in FutureTask, but instead in ScheduledFutureTask.