Java Reference
In-Depth Information
If, instead of letting the task finish normally, we click the Cancel button, the task will finish immediately and
the screenshot in Figure 7-10 results. Notice that the State field has the value CANCELLED now. The Value field
contains the string we passed to the updateValue() method when the task was cancelled. When we detect that the
task is cancelled, we have two choices of exiting from the method body. In the program in Listing 7-7, we chose to
update the Value and return from the method. We could also have chosen to exit from the method body by throwing
a RuntimeException . Had we made that choice, the screenshot would have an empty Value field but with a nonempty
Exception field. The state of the worker would have been CANCELLED either way.
Figure 7-10. The WorkerAndTaskExample program after the task has been cancelled
When you return normally in response to cancellation, a bug in the current implementation of Task causes
an IllegalStateException to be recorded as the exception of the Task . this will be fixed in the next release.
Caution
The final screenshot, Figure 7-11 , shows what happens when the Exception button is clicked when the task is
executing. We simulate an exception in the task by setting an AtomicBoolean flag from the JavaFX application, which
the task then picks up in the worker thread and throws the exception. Notice that the status field has the value FAILED
now. The Value field is empty because the task did not complete successfully. The Exception field is filled with the
message of the RuntimeException that we threw.
 
 
Search WWH ::




Custom Search