Search code examples
javamultithreadingswingworker

Java - Protect from interrupt SwingWorker


I need to interrupt swingworkers, but if the thread is running some fragment, it should interrupt after that. Something like this:

public class worker extends SwingWorker<Integer, String>{
    //(...) constructors and everything else

    protected Integer doInBackground() throws Exception{
        //Code that can be interrupted
        while(true){
            //(...) more code that can be interrupted

            //This shouldn't be interrupted, has to wait till the loop ends
            for(int i=0; i<10; i++){ 

            //(...) more code that can be interrupted
        }            
    }
}

Interrupting the worker with:

Worker worker = new Worker();
worker.execute();
worker.cancel(true);

I've tried synchronized blocks, but not sure if that doesn't work or i'm just doing it wrong.

Is there a way? Thanks!


Solution

  • Any way you can control either by a flag which will check the thread periodically. So before start you can check the flag or interrupt then Proceed.

    make flag as volatile so it will be visible to all thread or AtomicBoolean

     while (flag) {
           //do stuff here
         }
    

    or you can use interrupt to cancel the task.

     try {
          while(!Thread.currentThread().isInterrupted()) {
             // ...
          }
       } catch (InterruptedException consumed)
    
       }