<Swing Dev> Ways to cancel SwingWorker running task
Roman Kennke
roman at kennke.org
Tue Jul 12 22:43:42 UTC 2011
Hi,
> Can I use Thread.stop() to cancel a SwingWorker running task forcely?
> Though the stop method is documented as deprecated in JDK doc. My
> thought is, first store the thread in doInBackground, then force stop
> the thread by invoking thread.stop() later.
>
> The purpose is to guarantee to always stop the task within specified
> seconds(for example 20s). For some tasks, we can not achieve this goal
> using approaches, such as checking cancel flag or
> SwingWorker.cancel(true).
Calling cancel() will basically result in the worker thread to be
interrupted. If your task does not respond to thread interruption, it
will continue running. There's a very good article about thread
interruption:
http://www.ibm.com/developerworks/java/library/j-jtp05236/index.html
Make sure your task handles interruption in a timely manner, i.e. don't
just catch and ignore InterruptedException and if doing things in a
loop, check the interrupted flag of the thread regularily, and it should
cancel cleanly and fast. An exception is when the task is doing non
interruptible stuff like network connection, in which case you need to
either use the interruptible equivalent (i.e. NIO interruptible
channels) or implement your own solution to cancelling (e.g. call
shutdown() on a network socket).
Hope that helps,
Regards, Roman
More information about the swing-dev
mailing list