This answer uses the same concept as Daniel's answer.
Enclosed is a copy of the Partial Result sample from the Task javadoc (fixed for syntax errors currently embedded in the Java 8 javadoc and to add more specific Generic types). You can use a modification of that.
Place your exceptions in the partialResults collection. For your case, you don't need to return the list of exceptions from the Task, but can instead place them in some UI control which displays the exceptions (like a ListView
with a CellFactory
for exception display). Note that the partialResults collection did not need to be synchronized because it is always updated and accessed on the JavaFX UI thread (the update is happening via a Platform.runLater()
call similar to Daniel's solution).
public class PartialResultsTask extends Task<ObservableList<Rectangle>> {
private ReadOnlyObjectWrapper<ObservableList<Rectangle>> partialResults =
new ReadOnlyObjectWrapper<>(
this,
"partialResults",
FXCollections.observableArrayList(
new ArrayList<>()
)
);
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(() -> partialResults.get().add(r));
updateProgress(i, 100);
}
return partialResults.get();
}
}
When updating it's observable properties Task first checks if the update is occurring on the FX Application thread. If it is, it does an immediate update. If it is not, then it wraps the update in a Platform.runLater()
call. See the Task source code to understand how this is done.
Perhaps it would be possible to define a set of generic concurrent aware properties, but JavaFX does not provide such facilities at it's core. Indeed, it doesn't need to. With the exception of the javafx.concurrent package, JavaFX is a single threaded UI framework.