Camilo Guevara
Camilo Guevara

Reputation: 165

SwingWorker executes done() before finishing doInBackground()

I have been reading about this, and from these posts, I get that I might be a bug

SwingWorker, done() is executed before process() calls are finished

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

However in my case, there is nothing that calls the done method. This is how my worker works.

public static class collectingWorker extends SwingWorker<Void, Void> { 


    collectingWorker(String name) {
        //initialize
        threadName = name; 
    }

    @Override
    public Void doInBackground() {    

        loop = true;   
        while(loop){  
            //Code goes here
        }
        return null;
    }  

    @Override
    protected void done() {
        System.out.println("loop: " + loop);
        System.out.println("Collecting worker DONE");
        try {
            get();
        } catch (CancellationException x) {
            System.out.println("Cancelation");
            // ...
        } catch (InterruptedException x) {
            System.out.println("Interruption");
            // ...
        } catch (ExecutionException x) {
            System.out.println("Execution");
            System.out.println(x.getMessage());
            System.out.println(x.getCause());
            // ...
        }
    }
} 

And on a separate thread, I have a counter that waits x minutes before setting loop to false. What I see is that collectingWorker done method is executed before the x minutes that it should have waited, and to make things worse, it is completely random, sometimes it works, sometimes it fails after 3 minutes, sometimes it fails after 90 minutes.

And this is what I get from the prints in the done method, as you can see, the boolean "loop" is never set to false

loop: true
Collecting worker DONE
Execution
java.util.NoSuchElementException
java.util.NoSuchElementException

Any ideas or workarounds?

Upvotes: 1

Views: 299

Answers (1)

jdb1015
jdb1015

Reputation: 145

The logic nested within your while(loop) is throwing a NoSuchElementException causing your entire doInBackground() method to exit prematurely.

Upvotes: 1

Related Questions