Alex Rivera | Logout

SwingWorker: when exactly is called done method?

Asked 2011-06-01T15:59:26.073
21

Javadoc of the done() method of SwingWorker:

Executed on the Event Dispatch Thread after the doInBackground method is finished.

I've clues that it is not true in the case of canceled worker.
Done is called in each case (normal termination or cancellation) but when cancelled it is not enqueued to the EDT, as it happens for normal termination.

Is there some more precise analisis on when done is called in the case that a SwingWorker is cancelled?

Clarification: this question is NOT on how to cancel a SwingWorker. Here it is assumed that the SwingWorker is cancelled in the right way.
And it is NOT about thread still working when they are supposed to be finished.

Edit
Report

1 Answer

6

done() is called in any case, wether the worker is cancelled or it finishes normally. Nevertheless there are cases where the doInBackground is still running and the done method is called already (this is done inside cancel() no matter if the thread already finished). A simple example can be found here:

public static void main(String[] args) throws AWTException {
    SwingWorker<Void, Void> sw = new SwingWorker<Void, Void>() {

        protected Void doInBackground() throws Exception {
            System.out.println("start");
            Thread.sleep(2000);
            System.out.println("end");
            return null;
        }

        protected void done() {
            System.out.println("done " + isCancelled());
        }
    };
    sw.execute();
    try {
        Thread.sleep(1000);
        sw.cancel(false);
        Thread.sleep(10000);
    } catch (InterruptedException ex) {
        ex.printStackTrace();
    }

Thus it can be the case that done is called before doInBackground finishes.

answered 2011-06-01T16:34:45.427

Your Answer