Module javafx.graphics
Package javafx.concurrent

# Class Task<V>

java.lang.Object
java.util.concurrent.FutureTask<V>
javafx.concurrent.Task<V>

All Implemented Interfaces:
  `Runnable`, `Future<V>`, `RunnableFuture<V>`, `Worker<V>`, `EventTarget`

public abstract class Task<V> extends FutureTask<V> implements Worker<V>, EventTarget

A fully observable implementation of a `FutureTask`. `Task` exposes additional state and observable properties useful for programming asynchronous tasks in JavaFX, as defined in the `Worker` interface. An implementation of Task must override the `call()` method. This method is invoked on the background thread. Any state which is used in this method must be safe to read and write from a background thread. For example, manipulating a live scene graph from this method is unsafe and will result in runtime exceptions.

Tasks are flexible and extremely useful for the encapsulation of "work". Because `Service` is designed to execute a Task, any Tasks defined by the application or library code can easily be used with a Service. Likewise, since Task extends from FutureTask, it is very easy and natural to use a Task with the java concurrency `Executor` API. Since a Task is Runnable, you can also call it directly (by invoking the `FutureTask.run()` method) from another background thread. This allows for composition of work, or pass it to a new Thread constructed and executed manually. Finally, since you can manually create a new Thread, passing it a Runnable, it is possible to use the following idiom:

             Thread th = new Thread(task);
             th.setDaemon(true);
             th.start();

Note that this code sets the daemon flag of the Thread to true. If you want a background thread to prevent the VM from exiting after the last stage is closed, then you would want daemon to be false. However, if you want the background threads to simply terminate after all the stages are closed, then you must set daemon to true.

Although `ExecutorService` defines several methods which take a Runnable, you should generally limit yourself to using the `execute` method inherited from `Executor`.

As with FutureTask, a Task is a one-shot class and cannot be reused. See `Service` for a reusable `Worker`.

Because the Task is designed for use with JavaFX GUI applications, it ensures that every change to its public properties, as well as change notifications for state, errors, and for event handlers, all occur on the main JavaFX application thread. Accessing these properties from a background thread (including the `call()` method) will result in runtime exceptions being raised. The only exception to this, is when initially configuring a Task, which may safely be done from any thread. However, once the Task has been initialized and started, it may only thereafter be used from the FX thread (except for those methods clearly marked as being appropriate for the subclass to invoke from the background thread).

It is strongly encouraged that all Tasks be initialized with immutable state upon which the Task will operate. This should be done by providing a Task constructor which takes the parameters necessary for execution of the Task. Immutable state makes it easy and safe to use from any thread and ensures correctness in the presence of multiple threads.

In Java there is no reliable way to "kill" a thread in process. However, when `cancel` is called on a Task, it is important that the Task stop processing. A "run-away" Task might continue processing and updating the message, text, and progress properties even after the Task has been cancelled! In Java, cancelling a Task is a cooperative endeavor. The user of the Task will request that it be cancelled, and the author of the Task must check whether is has been cancelled within the body of the `call` method. There are two ways this can be done. First, the Task author may check the isCancelled method, inherited from `FutureTask`, to see whether the Task has been cancelled. Second, if the Task implementation makes use of any blocking calls (such as NIO InterruptibleChannels or Thread.sleep) and the task is cancelled while in such a blocking call, an InterruptedException is thrown. Task implementations which have blocking calls should recognize that an interrupted thread may be the signal for a cancelled task and should double check the isCancelled method to ensure that the InterruptedException was thrown due to the cancellation of the Task.

## Examples

The following set of examples demonstrate some of the most common uses of Tasks.

### A Simple Loop

The first example is a simple loop that does nothing particularly useful, but demonstrates the fundamental aspects of writing a Task correctly. This example will simply loop and print to standard out on each loop iteration. When it completes, it returns the number of times it iterated.

         Task<Integer> task = new Task<Integer>() {
             @Override protected Integer call() throws Exception {
                 int iterations;
                 for (iterations = 0; iterations < 100000; iterations++) {
                     if (isCancelled()) {
                         break;
                     }
                     System.out.println("Iteration " + iterations);
                 }
                 return iterations;
             }
         };

First, we define what type of value is returned from this Task. In this case, we want to return the number of times we iterated, so we will specify the Task to be of type Integer by using generics. Then, within the implementation of the `call` method, we iterate from 0 to 100000. On each iteration, we check to see whether this Task has been cancelled. If it has been, then we break out of the loop and return the number of times we iterated. Otherwise a message is printed to the console and the iteration count increased and we continue looping.

Checking for isCancelled() in the loop body is critical, otherwise the developer may cancel the task, but the task will continue running and updating both the progress and returning the incorrect result from the end of the `call` method. A correct implementation of a Task will always check for cancellation.

### A Simple Loop With Progress Notification

Similar to the previous example, except this time we will modify the progress of the Task in each iteration. Note that we have a choice to make in the case of cancellation. Do we want to set the progress back to -1 (indeterminate) when the Task is cancelled, or do we want to leave the progress where it was at? In this case, let's leave the progress alone and only update the message on cancellation, though updating the progress after cancellation is a perfectly valid choice.

         Task<Integer> task = new Task<Integer>() {
             @Override protected Integer call() throws Exception {
                 int iterations;
                 for (iterations = 0; iterations < 10000000; iterations++) {
                     if (isCancelled()) {
                         updateMessage("Cancelled");
                         break;
                     }
                     updateMessage("Iteration " + iterations);
                     updateProgress(iterations, 10000000);
                 }
                 return iterations;
             }
         };

As before, within the for loop we check whether the Task has been cancelled. If it has been cancelled, we will update the Task's message to indicate that it has been cancelled, and then break as before. If the Task has not been cancelled, then we will update its message to indicate the current iteration and then update the progress to indicate the current progress.

### A Simple Loop With Progress Notification And Blocking Calls

This example adds to the previous examples a blocking call. Because a blocking call may thrown an InterruptedException, and because an InterruptedException may occur as a result of the Task being cancelled, we need to be sure to handle the InterruptedException and check on the cancel state.

         Task<Integer> task = new Task<Integer>() {
             @Override protected Integer call() throws Exception {
                 int iterations;
                 for (iterations = 0; iterations < 1000; iterations++) {
                     if (isCancelled()) {
                         updateMessage("Cancelled");
                         break;
                     }
                     updateMessage("Iteration " + iterations);
                     updateProgress(iterations, 1000);

                     // Now block the thread for a short time, but be sure
                     // to check the interrupted exception for cancellation!
                     try {
                         Thread.sleep(100);
                     } catch (InterruptedException interrupted) {
                         if (isCancelled()) {
                             updateMessage("Cancelled");
                             break;
                         }
                     }
                 }
                 return iterations;
             }
         };

Here we have added to the body of the loop a `Thread.sleep` call. Since this is a blocking call, I have to handle the potential InterruptedException. Within the catch block, I will check whether the Task has been cancelled, and if so, update the message accordingly and break out of the loop.

### A Task Which Takes Parameters

Most Tasks require some parameters in order to do useful work. For example, a DeleteRecordTask needs the object or primary key to delete from the database. A ReadFileTask needs the URI of the file to be read. Because Tasks operate on a background thread, care must be taken to make sure the body of the `call` method does not read or modify any shared state. There are two techniques most useful for doing this: using final variables, and passing variables to a Task during construction.

When using a Task as an anonymous class, the most natural way to pass parameters to the Task is by using final variables. In this example, we pass to the Task the total number of times the Task should iterate.

         final int totalIterations = 9000000;
         Task<Integer> task = new Task<Integer>() {
             @Override protected Integer call() throws Exception {
                 int iterations;
                 for (iterations = 0; iterations < totalIterations; iterations++) {
                     if (isCancelled()) {
                         updateMessage("Cancelled");
                         break;
                     }
                     updateMessage("Iteration " + iterations);
                     updateProgress(iterations, totalIterations);
                 }
                 return iterations;
             }
         };

Since `totalIterations` is final, the `call` method can safely read it and refer to it from a background thread.

When writing Task libraries (as opposed to specific-use implementations), we need to use a different technique. In this case, I will create an IteratingTask which performs the same work as above. This time, since the IteratingTask is defined in its own file, it will need to have parameters passed to it in its constructor. These parameters are assigned to final variables.

         public class IteratingTask extends Task<Integer> {
             private final int totalIterations;

             public IteratingTask(int totalIterations) {
                 this.totalIterations = totalIterations;
             }

             @Override protected Integer call() throws Exception {
                 int iterations = 0;
                 for (iterations = 0; iterations < totalIterations; iterations++) {
                     if (isCancelled()) {
                         updateMessage("Cancelled");
                         break;
                     }
                     updateMessage("Iteration " + iterations);
                     updateProgress(iterations, totalIterations);
                 }
                 return iterations;
             }
         }

And then when used:

         IteratingTask task = new IteratingTask(8000000);

In this way, parameters are passed to the IteratingTask in a safe manner, and again, are final. Thus, the `call` method can safely read this state from a background thread.

WARNING: Do not pass mutable state to a Task and then operate on it from a background thread. Doing so may introduce race conditions. In particular, suppose you had a SaveCustomerTask which took a Customer in its constructor. Although the SaveCustomerTask may have a final reference to the Customer, if the Customer object is mutable, then it is possible that both the SaveCustomerTask and some other application code will be reading or modifying the state of the Customer from different threads. Be very careful in such cases, that while a mutable object such as this Customer is being used from a background thread, that it is not being used also from another thread. In particular, if the background thread is reading data from the database and updating the Customer object, and the Customer object is bound to scene graph nodes (such as UI controls), then there could be a violation of threading rules! For such cases, modify the Customer object from the FX Application Thread rather than from the background thread.

         public class UpdateCustomerTask extends Task<Customer> {
             private final Customer customer;

             public UpdateCustomerTask(Customer customer) {
                 this.customer = customer;
             }

             @Override protected Customer call() throws Exception {
                 // pseudo-code:
                 //   query the database
                 //   read the values

                 // Now update the customer
                 Platform.runLater(new Runnable() {
                     @Override public void run() {
                         customer.setFirstName(rs.getString("FirstName"));
                         // etc
                     }
                 });

                 return customer;
             }
         }

### A Task Which Returns No Value

Many, if not most, Tasks should return a value upon completion. For CRUD Tasks, one would expect that a "Create" Task would return the newly created object or primary key, a "Read" Task would return the read object, an "Update" task would return the number of records updated, and a "Delete" task would return the number of records deleted.

However sometimes there just isn't anything truly useful to return. For example, I might have a Task which writes to a file. Task has built into it a mechanism for indicating whether it has succeeded or failed along with the number of bytes written (the progress), and thus there is nothing really for me to return. In such a case, you can use the Void type. This is a special type in the Java language which can only be assigned the value of `null`. You would use it as follows:

         final String filePath = "/foo.txt";
         final String contents = "Some contents";
         Task<Void> task = new Task<Void>() {
             @Override protected Void call() throws Exception {
                 File file = new File(filePath);
                 FileOutputStream out = new FileOutputStream(file);
                 // ... and other code to write the contents ...

                 // Return null at the end of a Task of type Void
                 return null;
             }
         };

### A Task Which Returns An ObservableList

Because the ListView, TableView, and other UI controls and scene graph nodes make use of ObservableList, it is common to want to create and return an ObservableList from a Task. When you do not care to display intermediate values, the easiest way to correctly write such a Task is simply to construct an ObservableList within the `call` method, and then return it at the conclusion of the Task.

         Task<ObservableList<Rectangle>> task = new Task<ObservableList<Rectangle>>() {
             @Override protected ObservableList<Rectangle> call() throws Exception {
                 updateMessage("Creating Rectangles");
                 ObservableList<Rectangle> results = FXCollections.observableArrayList();
                 for (int i=0; i<100; i++) {
                     if (isCancelled()) break;
                     Rectangle r = new Rectangle(10, 10);
                     r.setX(10 * i);
                     results.add(r);
                     updateProgress(i, 100);
                 }
                 return results;
             }
         };

In the above example, we are going to create 100 rectangles and return them from this task. An ObservableList is created within the `call` method, populated, and then returned.

### A Task Which Returns Partial Results

Sometimes you want to create a Task which will return partial results. Perhaps you are building a complex scene graph and want to show the scene graph as it is being constructed. Or perhaps you are reading a large amount of data over the network and want to display the entries in a TableView as the data is arriving. In such cases, there is some shared state available both to the FX Application Thread and the background thread. Great care must be taken to never update shared state from any thread other than the FX Application Thread.

The easiest way to do this is to take advantage of the `updateValue(Object)` method. This method may be called repeatedly from the background thread. Updates are coalesced to prevent saturation of the FX event queue. This means you can call it as frequently as you like from the background thread but only the most recent set is ultimately set.

         Task<Long> task = new Task<Long>() {
             @Override protected Long call() throws Exception {
                 long a = 0;
                 long b = 1;
                 for (long i = 0; i < Long.MAX_VALUE; i++) {
                     updateValue(a);
                     a += b;
                     b = a - b;
                 }
                 return a;
             }
         };

Another way to do this is to expose a new property on the Task which will represent the partial result. Then make sure to use `Platform.runLater` when updating the partial result.

         Task<Long> task = new Task<Long>() {
             @Override protected Long call() throws Exception {
                 long a = 0;
                 long b = 1;
                 for (long i = 0; i < Long.MAX_VALUE; i++) {
                     final long v = a;
                     Platform.runLater(new Runnable() {
                         @Override public void run() {
                             updateValue(v);
                         }
                     }
                     a += b;
                     b = a - b;
                 }
                 return a;
             }
         };

Suppose instead of updating a single value, you want to populate an ObservableList with results as they are obtained. One approach is to expose a new property on the Task which will represent the partial result. Then make sure to use `Platform.runLater` when adding new items to the partial result.

         public class PartialResultsTask extends Task<ObservableList<Rectangle>> {
             // Uses Java 7 diamond operator
             private ReadOnlyObjectWrapper<ObservableList<Rectangle>> partialResults =
                     new ReadOnlyObjectWrapper<>(this, "partialResults",
                             FXCollections.observableArrayList(new ArrayList<Rectangle>()));

             public final ObservableList<Rectangle> getPartialResults() { return partialResults.get(); }
             public final ReadOnlyObjectProperty<ObservableList<Rectangle>> partialResultsProperty() {
                 return partialResults.getReadOnlyProperty();
             }

             @Override protected ObservableList<Rectangle> call() throws Exception {
                 updateMessage("Creating Rectangles...");
                 for (int i=0; i<100; i++) {
                     if (isCancelled()) break;
                     final Rectangle r = new Rectangle(10, 10);
                     r.setX(10 * i);
                     Platform.runLater(new Runnable() {
                         @Override public void run() {
                             partialResults.get().add(r);
                         }
                     });
                     updateProgress(i, 100);
                 }
                 return partialResults.get();
             }
         }

### A Task Which Modifies The Scene Graph

Generally, Tasks should not interact directly with the UI. Doing so creates a tight coupling between a specific Task implementation and a specific part of your UI. However, when you do want to create such a coupling, you must ensure that you use `Platform.runLater` so that any modifications of the scene graph occur on the FX Application Thread.

         final Group group = new Group();
         Task<Void> task = new Task<Void>() {
             @Override protected Void call() throws Exception {
                 for (int i=0; i<100; i++) {
                     if (isCancelled()) break;
                     final Rectangle r = new Rectangle(10, 10);
                     r.setX(10 * i);
                     Platform.runLater(new Runnable() {
                         @Override public void run() {
                             group.getChildren().add(r);
                         }
                     });
                 }
                 return null;
             }
         };

### Reacting To State Changes Generically

Sometimes you may want to write a Task which updates its progress, message, text, or in some other way reacts whenever a state change happens on the Task. For example, you may want to change the status message on the Task on Failure, Success, Running, or Cancelled state changes.

         Task<Integer> task = new Task<Integer>() {
             @Override protected Integer call() throws Exception {
                 int iterations = 0;
                 for (iterations = 0; iterations < 100000; iterations++) {
                     if (isCancelled()) {
                         break;
                     }
                     System.out.println("Iteration " + iterations);
                 }
                 return iterations;
             }

             @Override protected void succeeded() {
                 super.succeeded();
                 updateMessage("Done!");
             }

             @Override protected void cancelled() {
                 super.cancelled();
                 updateMessage("Cancelled!");
             }

             @Override protected void failed() {
                 super.failed();
                 updateMessage("Failed!");
             }
         };

Since:
  JavaFX 2.0

- ## Property Summary

  Properties
  Type
  Property
  Description
  `final ReadOnlyObjectProperty<Throwable>`
  `exception`
  Gets the ReadOnlyObjectProperty representing any exception which occurred.
  `final ReadOnlyStringProperty`
  `message`
  Gets the ReadOnlyStringProperty representing the message.
  `final ObjectProperty<EventHandler<WorkerStateEvent>>`
  `onCancelled`
  The onCancelled event handler is called whenever the Task state transitions to the CANCELLED state.
  `final ObjectProperty<EventHandler<WorkerStateEvent>>`
  `onFailed`
  The onFailed event handler is called whenever the Task state transitions to the FAILED state.
  `final ObjectProperty<EventHandler<WorkerStateEvent>>`
  `onRunning`
  The onRunning event handler is called whenever the Task state transitions to the RUNNING state.
  `final ObjectProperty<EventHandler<WorkerStateEvent>>`
  `onScheduled`
  The onSchedule event handler is called whenever the Task state transitions to the SCHEDULED state.
  `final ObjectProperty<EventHandler<WorkerStateEvent>>`
  `onSucceeded`
  The onSucceeded event handler is called whenever the Task state transitions to the SUCCEEDED state.
  `final ReadOnlyDoubleProperty`
  `progress`
  Gets the ReadOnlyDoubleProperty representing the progress.
  `final ReadOnlyBooleanProperty`
  `running`
  Gets the ReadOnlyBooleanProperty representing whether the Worker is running.
  `final ReadOnlyObjectProperty<Worker.State>`
  `state`
  Gets the ReadOnlyObjectProperty representing the current state.
  `final ReadOnlyStringProperty`
  `title`
  Gets the ReadOnlyStringProperty representing the title.
  `final ReadOnlyDoubleProperty`
  `totalWork`
  Gets the ReadOnlyDoubleProperty representing the maximum amount of work that needs to be done.
  `final ReadOnlyObjectProperty<V>`
  `value`
  Gets the ReadOnlyObjectProperty representing the value.
  `final ReadOnlyDoubleProperty`
  `workDone`
  Gets the ReadOnlyDoubleProperty representing the current progress.

- ## Nested Class Summary

  ## Nested classes/interfaces declared in interface java.util.concurrent.Future

  `Future.State`

  ## Nested classes/interfaces declared in interface javafx.concurrent.Worker

  `Worker.State`

- ## Constructor Summary

  Constructors
  Constructor
  Description
  `Task()`
  Creates a new Task.

- ## Method Summary

  Modifier and Type
  Method
  Description
  `final <T extends Event>
  void`
  `addEventFilter(EventType<T> eventType, EventHandler<? super T> eventFilter)`
  Registers an event filter to this task.
  `final <T extends Event>
  void`
  `addEventHandler(EventType<T> eventType, EventHandler<? super T> eventHandler)`
  Registers an event handler to this task.
  `EventDispatchChain`
  `buildEventDispatchChain(EventDispatchChain tail)`
  Construct an event dispatch chain for this target.
  `protected abstract V`
  `call()`
  Invoked when the Task is executed, the call method must be overridden and implemented by subclasses.
  `final boolean`
  `cancel()`
  Terminates execution of this Worker.
  `protected void`
  `cancelled()`
  A protected convenience method for subclasses, called whenever the state of the Task has transitioned to the CANCELLED state.
  `final ReadOnlyObjectProperty<Throwable>`
  `exceptionProperty()`
  Gets the ReadOnlyObjectProperty representing any exception which occurred.
  `protected void`
  `failed()`
  A protected convenience method for subclasses, called whenever the state of the Task has transitioned to the FAILED state.
  `final void`
  `fireEvent(Event event)`
  Fires the specified event.
  `final Throwable`
  `getException()`
  Gets the value of the `exception` property.
  `final String`
  `getMessage()`
  Gets the value of the `message` property.
  `final EventHandler<WorkerStateEvent>`
  `getOnCancelled()`
  The onCancelled event handler is called whenever the Task state transitions to the CANCELLED state.
  `final EventHandler<WorkerStateEvent>`
  `getOnFailed()`
  The onFailed event handler is called whenever the Task state transitions to the FAILED state.
  `final EventHandler<WorkerStateEvent>`
  `getOnRunning()`
  The onRunning event handler is called whenever the Task state transitions to the RUNNING state.
  `final EventHandler<WorkerStateEvent>`
  `getOnScheduled()`
  The onSchedule event handler is called whenever the Task state transitions to the SCHEDULED state.
  `final EventHandler<WorkerStateEvent>`
  `getOnSucceeded()`
  The onSucceeded event handler is called whenever the Task state transitions to the SUCCEEDED state.
  `final double`
  `getProgress()`
  Gets the value of the `progress` property.
  `final Worker.State`
  `getState()`
  Gets the value of the `state` property.
  `final String`
  `getTitle()`
  Gets the value of the `title` property.
  `final double`
  `getTotalWork()`
  Gets the value of the `totalWork` property.
  `final V`
  `getValue()`
  Gets the value of the `value` property.
  `final double`
  `getWorkDone()`
  Gets the value of the `workDone` property.
  `final boolean`
  `isRunning()`
  Gets the value of the `running` property.
  `final ReadOnlyStringProperty`
  `messageProperty()`
  Gets the ReadOnlyStringProperty representing the message.
  `final ObjectProperty<EventHandler<WorkerStateEvent>>`
  `onCancelledProperty()`
  The onCancelled event handler is called whenever the Task state transitions to the CANCELLED state.
  `final ObjectProperty<EventHandler<WorkerStateEvent>>`
  `onFailedProperty()`
  The onFailed event handler is called whenever the Task state transitions to the FAILED state.
  `final ObjectProperty<EventHandler<WorkerStateEvent>>`
  `onRunningProperty()`
  The onRunning event handler is called whenever the Task state transitions to the RUNNING state.
  `final ObjectProperty<EventHandler<WorkerStateEvent>>`
  `onScheduledProperty()`
  The onSchedule event handler is called whenever the Task state transitions to the SCHEDULED state.
  `final ObjectProperty<EventHandler<WorkerStateEvent>>`
  `onSucceededProperty()`
  The onSucceeded event handler is called whenever the Task state transitions to the SUCCEEDED state.
  `final ReadOnlyDoubleProperty`
  `progressProperty()`
  Gets the ReadOnlyDoubleProperty representing the progress.
  `final <T extends Event>
  void`
  `removeEventFilter(EventType<T> eventType, EventHandler<? super T> eventFilter)`
  Unregisters a previously registered event filter from this task.
  `final <T extends Event>
  void`
  `removeEventHandler(EventType<T> eventType, EventHandler<? super T> eventHandler)`
  Unregisters a previously registered event handler from this task.
  `protected void`
  `running()`
  A protected convenience method for subclasses, called whenever the state of the Task has transitioned to the RUNNING state.
  `final ReadOnlyBooleanProperty`
  `runningProperty()`
  Gets the ReadOnlyBooleanProperty representing whether the Worker is running.
  `protected void`
  `scheduled()`
  A protected convenience method for subclasses, called whenever the state of the Task has transitioned to the SCHEDULED state.
  `protected final <T extends Event>
  void`
  `setEventHandler(EventType<T> eventType, EventHandler<? super T> eventHandler)`
  Sets the handler to use for this event type.
  `final void`
  `setOnCancelled(EventHandler<WorkerStateEvent> value)`
  The onCancelled event handler is called whenever the Task state transitions to the CANCELLED state.
  `final void`
  `setOnFailed(EventHandler<WorkerStateEvent> value)`
  The onFailed event handler is called whenever the Task state transitions to the FAILED state.
  `final void`
  `setOnRunning(EventHandler<WorkerStateEvent> value)`
  The onRunning event handler is called whenever the Task state transitions to the RUNNING state.
  `final void`
  `setOnScheduled(EventHandler<WorkerStateEvent> value)`
  The onSchedule event handler is called whenever the Task state transitions to the SCHEDULED state.
  `final void`
  `setOnSucceeded(EventHandler<WorkerStateEvent> value)`
  The onSucceeded event handler is called whenever the Task state transitions to the SUCCEEDED state.
  `final ReadOnlyObjectProperty<Worker.State>`
  `stateProperty()`
  Gets the ReadOnlyObjectProperty representing the current state.
  `protected void`
  `succeeded()`
  A protected convenience method for subclasses, called whenever the state of the Task has transitioned to the SUCCEEDED state.
  `final ReadOnlyStringProperty`
  `titleProperty()`
  Gets the ReadOnlyStringProperty representing the title.
  `final ReadOnlyDoubleProperty`
  `totalWorkProperty()`
  Gets the ReadOnlyDoubleProperty representing the maximum amount of work that needs to be done.
  `protected void`
  `updateMessage(String message)`
  Updates the `message` property.
  `protected void`
  `updateProgress(double workDone, double max)`
  Updates the `workDone`, `totalWork`, and `progress` properties.
  `protected void`
  `updateProgress(long workDone, long max)`
  Updates the `workDone`, `totalWork`, and `progress` properties.
  `protected void`
  `updateTitle(String title)`
  Updates the `title` property.
  `protected void`
  `updateValue(V value)`
  Updates the `value` property.
  `final ReadOnlyObjectProperty<V>`
  `valueProperty()`
  Gets the ReadOnlyObjectProperty representing the value.
  `final ReadOnlyDoubleProperty`
  `workDoneProperty()`
  Gets the ReadOnlyDoubleProperty representing the current progress.

  ### Methods declared in class java.util.concurrent.FutureTask

  `cancel, done, exceptionNow, get, get, isCancelled, isDone, resultNow, run, runAndReset, set, setException, state, toString`

  ### Methods declared in class java.lang.Object

  `clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait`

- ## Property Details

  - ### state

    public final ReadOnlyObjectProperty<Worker.State> stateProperty
    Specified by:
      `stateProperty` in interface `Worker<V>`
    Returns:
      The property representing the state
    See Also:
      - `getState()`
      - `stateProperty()`

  - ### onScheduled

    public final ObjectProperty<EventHandler<WorkerStateEvent>> onScheduledProperty
    The onSchedule event handler is called whenever the Task state transitions to the SCHEDULED state.
    Since:
      JavaFX 2.1
    See Also:
      - `getOnScheduled()`
      - `setOnScheduled(EventHandler)`
      - `onScheduledProperty()`

  - ### onRunning

    public final ObjectProperty<EventHandler<WorkerStateEvent>> onRunningProperty
    The onRunning event handler is called whenever the Task state transitions to the RUNNING state.
    Since:
      JavaFX 2.1
    See Also:
      - `getOnRunning()`
      - `setOnRunning(EventHandler)`
      - `onRunningProperty()`

  - ### onSucceeded

    public final ObjectProperty<EventHandler<WorkerStateEvent>> onSucceededProperty
    The onSucceeded event handler is called whenever the Task state transitions to the SUCCEEDED state.
    Since:
      JavaFX 2.1
    See Also:
      - `getOnSucceeded()`
      - `setOnSucceeded(EventHandler)`
      - `onSucceededProperty()`

  - ### onCancelled

    public final ObjectProperty<EventHandler<WorkerStateEvent>> onCancelledProperty
    The onCancelled event handler is called whenever the Task state transitions to the CANCELLED state.
    Since:
      JavaFX 2.1
    See Also:
      - `getOnCancelled()`
      - `setOnCancelled(EventHandler)`
      - `onCancelledProperty()`

  - ### onFailed

    public final ObjectProperty<EventHandler<WorkerStateEvent>> onFailedProperty
    The onFailed event handler is called whenever the Task state transitions to the FAILED state.
    Since:
      JavaFX 2.1
    See Also:
      - `getOnFailed()`
      - `setOnFailed(EventHandler)`
      - `onFailedProperty()`

  - ### value

    public final ReadOnlyObjectProperty<V> valueProperty
    Specified by:
      `valueProperty` in interface `Worker<V>`
    Returns:
      The property representing the current value
    See Also:
      - `getValue()`
      - `valueProperty()`

  - ### exception

    public final ReadOnlyObjectProperty<Throwable> exceptionProperty
    Specified by:
      `exceptionProperty` in interface `Worker<V>`
    Returns:
      the property representing the exception
    See Also:
      - `getException()`
      - `exceptionProperty()`

  - ### workDone

    public final ReadOnlyDoubleProperty workDoneProperty
    Specified by:
      `workDoneProperty` in interface `Worker<V>`
    Returns:
      The property representing the amount of work done
    See Also:
      - `getWorkDone()`
      - `workDoneProperty()`

  - ### totalWork

    public final ReadOnlyDoubleProperty totalWorkProperty
    Specified by:
      `totalWorkProperty` in interface `Worker<V>`
    Returns:
      the property representing the total work to be done
    See Also:
      - `getTotalWork()`
      - `totalWorkProperty()`

  - ### progress

    public final ReadOnlyDoubleProperty progressProperty
    Specified by:
      `progressProperty` in interface `Worker<V>`
    Returns:
      the property representing the progress
    See Also:
      - `getProgress()`
      - `progressProperty()`

  - ### running

    public final ReadOnlyBooleanProperty runningProperty
    Specified by:
      `runningProperty` in interface `Worker<V>`
    Returns:
      the property representing whether the worker is running
    See Also:
      - `isRunning()`
      - `runningProperty()`

  - ### message

    public final ReadOnlyStringProperty messageProperty
    Specified by:
      `messageProperty` in interface `Worker<V>`
    Returns:
      a property representing the current message
    See Also:
      - `getMessage()`
      - `messageProperty()`

  - ### title

    public final ReadOnlyStringProperty titleProperty
    Specified by:
      `titleProperty` in interface `Worker<V>`
    Returns:
      the property representing the current title
    See Also:
      - `getTitle()`
      - `titleProperty()`

- ## Constructor Details

  - ### Task

    public Task()
    Creates a new Task.

- ## Method Details

  - ### call

    protected abstract V call() throws Exception
    Invoked when the Task is executed, the call method must be overridden and implemented by subclasses. The call method actually performs the background thread logic. Only the updateProgress, updateMessage, updateValue and updateTitle methods of Task may be called from code within this method. Any other interaction with the Task from the background thread will result in runtime exceptions.
    Returns:
      The result of the background work, if any.
    Throws:
      `Exception` - an unhandled exception which occurred during the background operation

  - ### getState

    public final Worker.State getState()
    Gets the value of the `state` property.
    Specified by:
      `getState` in interface `Worker<V>`
    Property description:
    Returns:
      the value of the `state` property
    See Also:
      - `stateProperty()`

  - ### stateProperty

    public final ReadOnlyObjectProperty<Worker.State> stateProperty()
    Description copied from interface: `Worker`
    Gets the ReadOnlyObjectProperty representing the current state.
    Specified by:
      `stateProperty` in interface `Worker<V>`
    Returns:
      the `state` property
    See Also:
      - `getState()`

  - ### onScheduledProperty

    public final ObjectProperty<EventHandler<WorkerStateEvent>> onScheduledProperty()
    The onSchedule event handler is called whenever the Task state transitions to the SCHEDULED state.
    Returns:
      the onScheduled event handler property
    Since:
      JavaFX 2.1
    See Also:
      - `getOnScheduled()`
      - `setOnScheduled(EventHandler)`

  - ### getOnScheduled

    public final EventHandler<WorkerStateEvent> getOnScheduled()
    The onSchedule event handler is called whenever the Task state transitions to the SCHEDULED state.
    Returns:
      the onScheduled event handler, if any
    Since:
      JavaFX 2.1

  - ### setOnScheduled

    public final void setOnScheduled(EventHandler<WorkerStateEvent> value)
    The onSchedule event handler is called whenever the Task state transitions to the SCHEDULED state.
    Parameters:
      `value` - the event handler, can be null to clear it
    Since:
      JavaFX 2.1

  - ### scheduled

    protected void scheduled()
    A protected convenience method for subclasses, called whenever the state of the Task has transitioned to the SCHEDULED state. This method is invoked on the FX Application Thread after the Task has been fully transitioned to the new state.
    Since:
      JavaFX 2.1

  - ### onRunningProperty

    public final ObjectProperty<EventHandler<WorkerStateEvent>> onRunningProperty()
    The onRunning event handler is called whenever the Task state transitions to the RUNNING state.
    Returns:
      the onRunning event handler property
    Since:
      JavaFX 2.1
    See Also:
      - `getOnRunning()`
      - `setOnRunning(EventHandler)`

  - ### getOnRunning

    public final EventHandler<WorkerStateEvent> getOnRunning()
    The onRunning event handler is called whenever the Task state transitions to the RUNNING state.
    Returns:
      the onRunning event handler, if any
    Since:
      JavaFX 2.1

  - ### setOnRunning

    public final void setOnRunning(EventHandler<WorkerStateEvent> value)
    The onRunning event handler is called whenever the Task state transitions to the RUNNING state.
    Parameters:
      `value` - the event handler, can be null to clear it
    Since:
      JavaFX 2.1

  - ### running

    protected void running()
    A protected convenience method for subclasses, called whenever the state of the Task has transitioned to the RUNNING state. This method is invoked on the FX Application Thread after the Task has been fully transitioned to the new state.
    Since:
      JavaFX 2.1

  - ### onSucceededProperty

    public final ObjectProperty<EventHandler<WorkerStateEvent>> onSucceededProperty()
    The onSucceeded event handler is called whenever the Task state transitions to the SUCCEEDED state.
    Returns:
      the onSucceeded event handler property
    Since:
      JavaFX 2.1
    See Also:
      - `getOnSucceeded()`
      - `setOnSucceeded(EventHandler)`

  - ### getOnSucceeded

    public final EventHandler<WorkerStateEvent> getOnSucceeded()
    The onSucceeded event handler is called whenever the Task state transitions to the SUCCEEDED state.
    Returns:
      the onSucceeded event handler, if any
    Since:
      JavaFX 2.1

  - ### setOnSucceeded

    public final void setOnSucceeded(EventHandler<WorkerStateEvent> value)
    The onSucceeded event handler is called whenever the Task state transitions to the SUCCEEDED state.
    Parameters:
      `value` - the event handler, can be null to clear it
    Since:
      JavaFX 2.1

  - ### succeeded

    protected void succeeded()
    A protected convenience method for subclasses, called whenever the state of the Task has transitioned to the SUCCEEDED state. This method is invoked on the FX Application Thread after the Task has been fully transitioned to the new state.
    Since:
      JavaFX 2.1

  - ### onCancelledProperty

    public final ObjectProperty<EventHandler<WorkerStateEvent>> onCancelledProperty()
    The onCancelled event handler is called whenever the Task state transitions to the CANCELLED state.
    Returns:
      the onCancelled event handler property
    Since:
      JavaFX 2.1
    See Also:
      - `getOnCancelled()`
      - `setOnCancelled(EventHandler)`

  - ### getOnCancelled

    public final EventHandler<WorkerStateEvent> getOnCancelled()
    The onCancelled event handler is called whenever the Task state transitions to the CANCELLED state.
    Returns:
      the onCancelled event handler, if any
    Since:
      JavaFX 2.1

  - ### setOnCancelled

    public final void setOnCancelled(EventHandler<WorkerStateEvent> value)
    The onCancelled event handler is called whenever the Task state transitions to the CANCELLED state.
    Parameters:
      `value` - the event handler, can be null to clear it
    Since:
      JavaFX 2.1

  - ### cancelled

    protected void cancelled()
    A protected convenience method for subclasses, called whenever the state of the Task has transitioned to the CANCELLED state. This method is invoked on the FX Application Thread after the Task has been fully transitioned to the new state.
    Since:
      JavaFX 2.1

  - ### onFailedProperty

    public final ObjectProperty<EventHandler<WorkerStateEvent>> onFailedProperty()
    The onFailed event handler is called whenever the Task state transitions to the FAILED state.
    Returns:
      the onFailed event handler property
    Since:
      JavaFX 2.1
    See Also:
      - `getOnFailed()`
      - `setOnFailed(EventHandler)`

  - ### getOnFailed

    public final EventHandler<WorkerStateEvent> getOnFailed()
    The onFailed event handler is called whenever the Task state transitions to the FAILED state.
    Returns:
      the onFailed event handler, if any
    Since:
      JavaFX 2.1

  - ### setOnFailed

    public final void setOnFailed(EventHandler<WorkerStateEvent> value)
    The onFailed event handler is called whenever the Task state transitions to the FAILED state.
    Parameters:
      `value` - the event handler, can be null to clear it
    Since:
      JavaFX 2.1

  - ### failed

    protected void failed()
    A protected convenience method for subclasses, called whenever the state of the Task has transitioned to the FAILED state. This method is invoked on the FX Application Thread after the Task has been fully transitioned to the new state.
    Since:
      JavaFX 2.1

  - ### getValue

    public final V getValue()
    Gets the value of the `value` property.
    Specified by:
      `getValue` in interface `Worker<V>`
    Property description:
    Returns:
      the value of the `value` property
    See Also:
      - `valueProperty()`

  - ### valueProperty

    public final ReadOnlyObjectProperty<V> valueProperty()
    Description copied from interface: `Worker`
    Gets the ReadOnlyObjectProperty representing the value.
    Specified by:
      `valueProperty` in interface `Worker<V>`
    Returns:
      the `value` property
    See Also:
      - `getValue()`

  - ### getException

    public final Throwable getException()
    Gets the value of the `exception` property.
    Specified by:
      `getException` in interface `Worker<V>`
    Property description:
    Returns:
      the value of the `exception` property
    See Also:
      - `exceptionProperty()`

  - ### exceptionProperty

    public final ReadOnlyObjectProperty<Throwable> exceptionProperty()
    Description copied from interface: `Worker`
    Gets the ReadOnlyObjectProperty representing any exception which occurred.
    Specified by:
      `exceptionProperty` in interface `Worker<V>`
    Returns:
      the `exception` property
    See Also:
      - `getException()`

  - ### getWorkDone

    public final double getWorkDone()
    Gets the value of the `workDone` property.
    Specified by:
      `getWorkDone` in interface `Worker<V>`
    Property description:
    Returns:
      the value of the `workDone` property
    See Also:
      - `workDoneProperty()`

  - ### workDoneProperty

    public final ReadOnlyDoubleProperty workDoneProperty()
    Description copied from interface: `Worker`
    Gets the ReadOnlyDoubleProperty representing the current progress.
    Specified by:
      `workDoneProperty` in interface `Worker<V>`
    Returns:
      the `workDone` property
    See Also:
      - `getWorkDone()`

  - ### getTotalWork

    public final double getTotalWork()
    Gets the value of the `totalWork` property.
    Specified by:
      `getTotalWork` in interface `Worker<V>`
    Property description:
    Returns:
      the value of the `totalWork` property
    See Also:
      - `totalWorkProperty()`

  - ### totalWorkProperty

    public final ReadOnlyDoubleProperty totalWorkProperty()
    Description copied from interface: `Worker`
    Gets the ReadOnlyDoubleProperty representing the maximum amount of work that needs to be done. These "work units" have meaning to the Worker implementation, such as the number of bytes that need to be downloaded or the number of images to process or some other such metric.
    Specified by:
      `totalWorkProperty` in interface `Worker<V>`
    Returns:
      the `totalWork` property
    See Also:
      - `getTotalWork()`

  - ### getProgress

    public final double getProgress()
    Gets the value of the `progress` property.
    Specified by:
      `getProgress` in interface `Worker<V>`
    Property description:
    Returns:
      the value of the `progress` property
    See Also:
      - `progressProperty()`

  - ### progressProperty

    public final ReadOnlyDoubleProperty progressProperty()
    Description copied from interface: `Worker`
    Gets the ReadOnlyDoubleProperty representing the progress.
    Specified by:
      `progressProperty` in interface `Worker<V>`
    Returns:
      the `progress` property
    See Also:
      - `getProgress()`

  - ### isRunning

    public final boolean isRunning()
    Gets the value of the `running` property.
    Specified by:
      `isRunning` in interface `Worker<V>`
    Property description:
    Returns:
      the value of the `running` property
    See Also:
      - `runningProperty()`

  - ### runningProperty

    public final ReadOnlyBooleanProperty runningProperty()
    Description copied from interface: `Worker`
    Gets the ReadOnlyBooleanProperty representing whether the Worker is running.
    Specified by:
      `runningProperty` in interface `Worker<V>`
    Returns:
      the `running` property
    See Also:
      - `isRunning()`

  - ### getMessage

    public final String getMessage()
    Gets the value of the `message` property.
    Specified by:
      `getMessage` in interface `Worker<V>`
    Property description:
    Returns:
      the value of the `message` property
    See Also:
      - `messageProperty()`

  - ### messageProperty

    public final ReadOnlyStringProperty messageProperty()
    Description copied from interface: `Worker`
    Gets the ReadOnlyStringProperty representing the message.
    Specified by:
      `messageProperty` in interface `Worker<V>`
    Returns:
      the `message` property
    See Also:
      - `getMessage()`

  - ### getTitle

    public final String getTitle()
    Gets the value of the `title` property.
    Specified by:
      `getTitle` in interface `Worker<V>`
    Property description:
    Returns:
      the value of the `title` property
    See Also:
      - `titleProperty()`

  - ### titleProperty

    public final ReadOnlyStringProperty titleProperty()
    Description copied from interface: `Worker`
    Gets the ReadOnlyStringProperty representing the title.
    Specified by:
      `titleProperty` in interface `Worker<V>`
    Returns:
      the `title` property
    See Also:
      - `getTitle()`

  - ### cancel

    public final boolean cancel()
    Description copied from interface: `Worker`
    Terminates execution of this Worker. Calling this method will either remove this Worker from the execution queue or stop execution.
    Specified by:
      `cancel` in interface `Worker<V>`
    Returns:
      returns true if the cancel was successful

  - ### updateProgress

    protected void updateProgress(long workDone, long max)
    Updates the `workDone`, `totalWork`, and `progress` properties. Calls to updateProgress are coalesced and run later on the FX application thread, and calls to updateProgress, even from the FX Application thread, may not necessarily result in immediate updates to these properties, and intermediate workDone values may be coalesced to save on event notifications. `max` becomes the new value for `totalWork`.

    This method is safe to be called from any thread.

    Parameters:
      `workDone` - A value from Long.MIN_VALUE up to max. If the value is greater than max, then it will be clamped at max. If the value passed is negative then the resulting percent done will be -1 (thus, indeterminate).
      `max` - A value from Long.MIN_VALUE to Long.MAX_VALUE.
    See Also:
      - `updateProgress(double, double)`

  - ### updateProgress

    protected void updateProgress(double workDone, double max)
    Updates the `workDone`, `totalWork`, and `progress` properties. Calls to updateProgress are coalesced and run later on the FX application thread, and calls to updateProgress, even from the FX Application thread, may not necessarily result in immediate updates to these properties, and intermediate workDone values may be coalesced to save on event notifications. `max` becomes the new value for `totalWork`.

    This method is safe to be called from any thread.

    Parameters:
      `workDone` - A value from Double.MIN_VALUE up to max. If the value is greater than max, then it will be clamped at max. If the value passed is negative, or Infinity, or NaN, then the resulting percentDone will be -1 (thus, indeterminate).
      `max` - A value from Double.MIN_VALUE to Double.MAX_VALUE. Infinity and NaN are treated as -1.
    Since:
      JavaFX 2.2

  - ### updateMessage

    protected void updateMessage(String message)
    Updates the `message` property. Calls to updateMessage are coalesced and run later on the FX application thread, so calls to updateMessage, even from the FX Application thread, may not necessarily result in immediate updates to this property, and intermediate message values may be coalesced to save on event notifications.

    This method is safe to be called from any thread.

    Parameters:
      `message` - the new message

  - ### updateTitle

    protected void updateTitle(String title)
    Updates the `title` property. Calls to updateTitle are coalesced and run later on the FX application thread, so calls to updateTitle, even from the FX Application thread, may not necessarily result in immediate updates to this property, and intermediate title values may be coalesced to save on event notifications.

    This method is safe to be called from any thread.

    Parameters:
      `title` - the new title

  - ### updateValue

    protected void updateValue(V value)
    Updates the `value` property. Calls to updateValue are coalesced and run later on the FX application thread, so calls to updateValue, even from the FX Application thread, may not necessarily result in immediate updates to this property, and intermediate values may be coalesced to save on event notifications.

    This method is safe to be called from any thread.

    Parameters:
      `value` - the new value
    Since:
      JavaFX 8.0

  - ### addEventHandler

    public final <T extends Event> void addEventHandler(EventType<T> eventType, EventHandler<? super T> eventHandler)
    Registers an event handler to this task. Any event filters are first processed, then the specified onFoo event handlers, and finally any event handlers registered by this method. As with other events in the scene graph, if an event is consumed, it will not continue dispatching.
    Type Parameters:
      `T` - the specific event class of the handler
    Parameters:
      `eventType` - the type of the events to receive by the handler
      `eventHandler` - the handler to register
    Throws:
      `NullPointerException` - if the event type or handler is null
    Since:
      JavaFX 2.1

  - ### removeEventHandler

    public final <T extends Event> void removeEventHandler(EventType<T> eventType, EventHandler<? super T> eventHandler)
    Unregisters a previously registered event handler from this task. One handler might have been registered for different event types, so the caller needs to specify the particular event type from which to unregister the handler.
    Type Parameters:
      `T` - the specific event class of the handler
    Parameters:
      `eventType` - the event type from which to unregister
      `eventHandler` - the handler to unregister
    Throws:
      `NullPointerException` - if the event type or handler is null
    Since:
      JavaFX 2.1

  - ### addEventFilter

    public final <T extends Event> void addEventFilter(EventType<T> eventType, EventHandler<? super T> eventFilter)
    Registers an event filter to this task. Registered event filters get an event before any associated event handlers.
    Type Parameters:
      `T` - the specific event class of the filter
    Parameters:
      `eventType` - the type of the events to receive by the filter
      `eventFilter` - the filter to register
    Throws:
      `NullPointerException` - if the event type or filter is null
    Since:
      JavaFX 2.1

  - ### removeEventFilter

    public final <T extends Event> void removeEventFilter(EventType<T> eventType, EventHandler<? super T> eventFilter)
    Unregisters a previously registered event filter from this task. One filter might have been registered for different event types, so the caller needs to specify the particular event type from which to unregister the filter.
    Type Parameters:
      `T` - the specific event class of the filter
    Parameters:
      `eventType` - the event type from which to unregister
      `eventFilter` - the filter to unregister
    Throws:
      `NullPointerException` - if the event type or filter is null
    Since:
      JavaFX 2.1

  - ### setEventHandler

    protected final <T extends Event> void setEventHandler(EventType<T> eventType, EventHandler<? super T> eventHandler)
    Sets the handler to use for this event type. There can only be one such handler specified at a time. This handler is guaranteed to be called first. This is used for registering the user-defined onFoo event handlers.
    Type Parameters:
      `T` - the specific event class of the handler
    Parameters:
      `eventType` - the event type to associate with the given eventHandler
      `eventHandler` - the handler to register, or null to unregister
    Throws:
      `NullPointerException` - if the event type is null
    Since:
      JavaFX 2.1

  - ### fireEvent

    public final void fireEvent(Event event)
    Fires the specified event. Any event filter encountered will be notified and can consume the event. If not consumed by the filters, the event handlers on this task are notified. If these don't consume the event either, then all event handlers are called and can consume the event.

    This method must be called on the FX user thread.

    Parameters:
      `event` - the event to fire
    Since:
      JavaFX 2.1

  - ### buildEventDispatchChain

    public EventDispatchChain buildEventDispatchChain(EventDispatchChain tail)
    Description copied from interface: `EventTarget`
    Construct an event dispatch chain for this target. The event dispatch chain contains event dispatchers which might be interested in processing of events targeted at this `EventTarget`. This event target is not automatically added to the chain, so if it wants to process events, it needs to add an `EventDispatcher` for itself to the chain.

    In the case the event target is part of some hierarchy, the chain for it is usually built from event dispatchers collected from the root of the hierarchy to the event target.

    The event dispatch chain is constructed by modifications to the provided initial event dispatch chain. The returned chain should have the initial chain at its end so the dispatchers should be prepended to the initial chain.

    The caller shouldn't assume that the initial chain remains unchanged nor that the returned value will reference a different chain.

    Specified by:
      `buildEventDispatchChain` in interface `EventTarget`
    Parameters:
      `tail` - the initial chain to build from
    Returns:
      the resulting event dispatch chain for this target