Biscuit128
Biscuit128

Reputation: 5398

Issues cancelling a swing worker

I am having some problems cancelling a swing worker. I am unsure after reading the documentation how to approach solving this

sw = new SwingWorker<Object, Void>()
{     
    Object o;
    protected Object doInBackground() throws Exception      
    {          
    //do some long running task via a method call
    } 
}

Then in my cancel button handler i just want to call sw.cancel(true);

This doesnt seem to be working though. According to the documentation the swing worker needs to no how to cancel iteslf. But, if the method to run the swing worker is only being calld once then how do i account for this with thread.sleep(which is what i've read is one way of fixing)

Thanks

Upvotes: 2

Views: 1691

Answers (2)

John Vint
John Vint

Reputation: 40256

Swing will actually monitor your work with a Future. When you try to cancel the worker Swing will invoke future.cancel(true) (the true value will attempt to interrupt() the executing thread).

What this means is your work needs to respond to interruption. If the long running computations don't respond to interruption you will have to put in some checkpoints and respond accordingly

protected Object doInBackground() throws Exception      
{          
   //do part 1 of long running task
   if(Thread.currentThread().isInterrupted()){
     //clean up and return
   }
   //do part 2 of long running task
   if(Thread.currentThread().isInterrupted()){
     //clean up and return
   }
   //etc..
} 

Swing will simply notify the executing thread that it should cancel. It is your responsibility to actually enforce cancellation.

Upvotes: 2

vaughandroid
vaughandroid

Reputation: 4374

There's a pretty good article here: http://blogs.oracle.com/swinger/entry/swingworker_stop_that_train

In brief, calling cancel() sets the thread's 'interrupted' flag. If you're doing I/O operations or calling Thread.sleep() then the flag gets checked in those and an InterruptedException will get thrown. If you do neither of those things, you can check it yourself using Thread.currentThread().isInterrupted() and throw the exception.

Upvotes: 1

Related Questions