title: NullPointerException: Timertask Cancel and Object Disposing
body: <p>This is my first time here. Please, excuse my bad English.</p>
  
  <p>I am writing here to ask a question about <code>TimerTask</code> and collateral effects of object disposing.</p>
  
  <p>Here is a simple example. This example shows a <code>JFrame</code> with a big button which starts a <code>TimerTask</code>. This task only writes a message, sleeps 6 seconds, and writes another message.</p>
  
  <p>Every 10 secs (it's not important this fact) the task is executed.</p>
  
  <p>If I click the button (when I know that the task is stopped and in the sleep method), the object writer (that let's us write a message) is set to null and the timer is cancelled.</p>
  
  <p>Then, if I cancel the task, and an execution of this task is running, it can be thrown <code>NullPointerException</code> (remember that writer was set to null).</p>
  
  <p>My question is: how can I avoid <code>NullPointerException</code> in this case? Catching it in the 
  run method of Timertask? or directly interrupting the task with interrupt method? </p>
  
  <p>Thank you for your understanding. </p>
  
  <pre><code>public class CancelTimer extends JFrame{
  
      public static void main(String[] args) {
          new CancelTimer().setVisible(true);
      }
  
      Timer timer;
  
      Writer writer;
  
      public CancelTimer()  {
          super();
  
          writer=new Writer();
  
          timer= new Timer("timer");
          timer.schedule(new TimerTask() {
              @Override
              public void run() {
                  try{
                  writer.print("Start and wait");
                      try {
                          Thread.sleep(6000);
                      } catch (InterruptedException e) {
                          e.printStackTrace();
                      }
                      writer.print("Bye, bye!");
                  } catch (NullPointerException e){
                      System.out.println("NullPointerException due external disposing task!");
                  }
              }
          }, 3000, 10000);
  
          JPanel panel = new JPanel(new BorderLayout());
          JButton button= new JButton();
          button.setAction(new AbstractAction() {
  
              @Override
              public void actionPerformed(ActionEvent e) {
                  writer=null;
                  timer.cancel();
  
              }
          });
          panel.add(button,BorderLayout.CENTER);
          this.setContentPane(panel);
          this.pack();
          this.setSize(new Dimension(400,400));
      }
  
      private class Writer {
          public void print(String text){
              System.out.println("PRINT SOME TEXT: "+text);
          }
  
      }
  
  
  }
  </code></pre>