2

The proper way to handle exceptions thrown by the doInBackground method of SwingWorker class is to invoke the get method from within the done method, as explained here and here.

The documentation for the get method states the following:

Waits if necessary for the computation to complete, and then retrieves its result.

Note: calling get on the Event Dispatch Thread blocks all events, including repaints, from being processed until this SwingWorker is complete.

Therefore, if the get method causes a waiting within the done method, in fact it would block the Event Dispatch Thread, since the done method is executed on EDT.

However, after performing a simple test of the proposed solution, you may notice that the EDT is not blocked: this behavior occurs because the get method is invoked within the done method, so get is invoked after the result of the operation was calculated, and therefore the call to it will not block the EDT. Is this motivation correct?

Community
  • 1
  • 1
enzom83
  • 8,080
  • 10
  • 68
  • 114

2 Answers2

3

Therefore, if the get method causes a waiting within the done method, in fact it would block the Event Dispatch Thread, since the done method is executed on EDT.

Actually, if done is called, the doInBackground has already returned, therefore calling get within done will NOT block the Event Dispatching Thread.

The same goes if you are using the PropertyChangeListener support and monitoring the change in state to DONE

Updated

So, after having a look at SwingWorker calls 'done' before the 'doInBackground' is finished, which would mean that calling get on a cancelled worker would block the EDT indeventially, the basic work around is actually to ignore the return result by checking the SwingWorker#isCancelled state. Let's face it, if the worker is cancelled, the return result is unknown/undefined, so it's best NOT to try and get it.

As an example (based on the code from the bug)

import java.util.concurrent.ExecutionException;
import javax.swing.SwingWorker;

public class Main {

    public static void main(String[] args) throws InterruptedException {
        SwingWorker<String, String> worker = new SwingWorker<String, String>() {
            @Override
            protected String doInBackground() throws Exception {
                try {
                    while (!Thread.currentThread().isInterrupted()) {
                        System.out.println("Working...");
                        Thread.sleep(1000);

                    }
                } catch (InterruptedException ex) {
                    System.out.println("Got interrupted!");
                }

                try {
                    System.out.println("Cleaning up");
                    Thread.sleep(10000);
                    System.out.println("Done cleaning");
                } catch (InterruptedException ex) {
                    System.out.println("Got interrupted second time!");
                }

                return null;
            }

            @Override
            protected void done() {
                System.out.println("Done");
                if (!isCancelled()) {
                    long start = System.currentTimeMillis();
                    try {
                        get();
                    } catch (InterruptedException | ExecutionException ex) {
                        ex.printStackTrace();
                    }
                    long end = System.currentTimeMillis();
                    System.out.println("Took " + ((end - start) / 1000d));
                } else {
                    System.out.println("Was cancelled");
                }
            }
        };

        worker.execute();

        Thread.sleep(10000);

        worker.cancel(true);
        Thread.sleep(20000);
    }
}
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • This may not hold if `cancel` is used. (bug) https://bugs.openjdk.java.net/browse/JDK-8081474 – Radiodef Sep 07 '15 at 21:50
  • @radiodef In theory, if cancelled, get "should" throw an InterruptedException. I'd be interested in knowingifnthis is just a bug in java 8 or not – MadProgrammer Sep 07 '15 at 22:00
  • I don't remember that much about the nature of the behavior, but I think it would be possible for `get` to block inside `done` if `cancel` is used. I encountered the bug on Java 6, so it's apparently been around for awhile. There's an older report as well. http://bugs.java.com/bugdatabase/view_bug.do?bug_id=6826514 – Radiodef Sep 07 '15 at 22:23
  • @Radiodef: the description of [`done`](http://docs.oracle.com/javase/7/docs/api/javax/swing/SwingWorker.html#done()) method states that _you can query status inside the implementation of this method to determine the result of this task or whether this task has been cancelled_. – enzom83 Sep 07 '15 at 22:39
  • @Radiodef Shows how often I cancel a `SwingWorker` – MadProgrammer Sep 07 '15 at 23:30
  • 2
    @enzom83 Yes, the issue I'm referring to, raised in the bug report links, is that `done` may be called before `doInBackground` returns if `cancel(true)` is used. Thinking about it again, I suppose that `get` wouldn't block in this case, it will throw `CancellationException` (like MadProgrammer must be referring to above). – Radiodef Sep 07 '15 at 23:35
  • 2
    @Radiodef Having tested the code from the bug report, the simple "work around" is to check the state of the `SwingWorker#isCancelled` property in the `done` method, if it is, then the "return" value is unknown/undefined and should not be gotten, otherwise, you can inspect it. As stated in the bug report response *"And to cancel the running task it should be canceleable i.e. be responsive to interruption"* - This would suggest that the Worker itself (in the `doInBackground` method) should be checking the `Thread.currentThread().isInterrupted()` or `isCancelled` state during it's work cycle – MadProgrammer Sep 07 '15 at 23:44
0
@Override
protected void done()
{
    try
    {
        if(!super.isCancelled())
        {
            super.get();
        }
    }
    catch(Exception ex)
    {
        ex.printStackTrace();
    }
}
jdb1015
  • 127
  • 6