0

Are the following two AssertionErrors placed right?

final Task<String> myTask = new Task<String>() {
    @Override
    protected String call() throws Exception {
        return "Lorem Ipsum";
    }

    @Override
    protected void succeeded() {
        super.succeeded();
        try {
            final String computedString = get();
        } catch (final InterruptedException | ExecutionException ex) {
            throw new AssertionError(
                    "Expected get() can called safely in succeeded");
        }
    }
};

myTask.setOnSucceeded(e -> {
    try {
        final String computedString = myTask.get();
    } catch (final Exception ex) {
        throw new AssertionError(
                "Expected get() can called safely in onSucceeded");
    }
});
Vertex
  • 2,682
  • 3
  • 29
  • 43

2 Answers2

0

In succeed(), you can be sure that get() doesn't block. It also shouldn't be possible to get an ExecutionException because that would have triggered failed().

But you can get an InterruptedException since other threads can send this signal at any time.

See this questions for details how to handle this specific exception: Handling InterruptedException in Java

Community
  • 1
  • 1
Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
0

Calling get() on the task in setOnSucceeded will be safe as, by the time the succeeded callback is invoked, the task has already completed, so it won't block at all and shouldn't show any exceptions at that time.

I think calling getValue() is preferred though as its semantics seem simpler. getValue is non-blocking, can't possibly throw InterruptedException or ExecutionException and ensures that it is only invoked on the JavaFX application thread, so it both simpler to understand and has additional safety checks.

jewelsea
  • 150,031
  • 14
  • 366
  • 406