The proper way to handle exceptions thrown by the SwingWorker.doInBackground

陌路散爱 提交于 2020-01-07 05:32:13

问题


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?


回答1:


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);
    }
}



回答2:


@Override
protected void done()
{
    try
    {
        if(!super.isCancelled())
        {
            super.get();
        }
    }
    catch(Exception ex)
    {
        ex.printStackTrace();
    }
}


来源:https://stackoverflow.com/questions/32445902/the-proper-way-to-handle-exceptions-thrown-by-the-swingworker-doinbackground

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!