Search code examples
javaswingworker

Stop long lasting method in SwingWorker doInBackground() on cancel()


There is a lot of information about how to cancel/stop a SwingWorker. However I can not find a proper solution on how to stop a long lasting method started within the doInBackround() method when cancel is invoked from the EDT.

For instance, if a recursive file search is started within the doInBackround() method using org.apache.commons.io.FileUtils.listFiles(file, FileUtils.getFileFilter(), DirectoryFileFilter.DIRECTORY);, and cancel(true) is invoked from the EDT, how can the file search be interrupted?


Solution

  • You need collaboration from the background task to be able to stop it. It should regularly check if the task has been cancelled and return as soon as possible if cancelled.

    So, either you reimplement the listFiles() method yourself and check at each iteration that the task hasbn't been cancelled, or you use a dirty trick, and throw some runtime exception from inside the file filter if the task has been cancelled (since the file filter will be invoked for every file the listFiles() method inspects.