Search code examples
javamultithreadingswtdispose

How do I stop a custom Thead in SWT application?


How do I stop a custom Thread when I exit my SWT application?

MyThread runs in an infinite loop, until a certain condition becomes true:

class MyThread extends Thread {

  @Override
  public void run() {
     do {
        // Do stuff...
     }
     while (!this.isInterrupted() && otherCondition);

}

In my SWT application I do start the thread and try to stop in in the SWT composite's dispose() method. However, this method is never called.

class MyComposite extends Composite {

    private MyThread myThread = null;

    @Override
    public void dispose() {
      super.dispose();

      if (null != this.myThread) {
         this.myThread.interrupt();
      }
    }

    public void somewhere() {
       this.myThread = new MyThread();
       this.myThread.start();
    }
}

Now, it can happen that I have closed my SWT application window already, but the thread keeps running (it still creates debug output). Isn't the dispose() method called automatically? What is the best way to make the thread stop, if the user closes the application window?


Solution

  • All controls are disposed when their parent window is closed, but not by calling their dispose method (an internal method called release is called). So as mentioned in another answer you need to use a DisposeListener to be informed about the dispose.

    Alternatively your thread can call setDaemon(true) - the JVM does not wait for daemon threads to stop when closing an application.