Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

SwingWorker done() is called before doInBackground is finished

843807Feb 3 2010 — edited Sep 10 2010
Hi,
I'm having a problem understanding how the SwingWorker works. According to java docs: "After the doInBackground method is finished the done method is executed" and there is a happens before relationship. But if I run the code below:
   public class A extends SwingWorker<Void, Void>
    {
    	protected Void doInBackground() throws InterruptedException
    	{
    		String k = "this is a test";
    		String j = k;
    		
    		while(true)
    		{
    			for(int i=0; i<1000; i++)
    			{
    				j = j + k;
    				j.replaceAll("nothing", "something");
    			}
    			
    			System.out.println("going");
    		}
    	}
    	
    	protected void done()
    	{
    		try
    		{
    			get();
    		}
    		catch(InterruptedException ex){System.out.println("interrupted");}
    		catch(CancellationException ex){System.out.println("cancelled");}

    		System.out.println("done");
    	}
}
and call cancel(true) while the thread is running the output I get is

going
going
cancelled
done
going
going
....

So that means that done() get's fired after I called cancel(), not after doInBackground() is finished.

This is causing some serious problems in my actual application, as I do some clean up in done(), but doInBackground() keeps going until it hits my Thread.sleep() code.

Thanks a lot.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Oct 8 2010
Added on Feb 3 2010
17 comments
2,042 views