title: How to stop threads of following type in Java used for watching folders for files using WatchService for folders by using jToggleButton
body: <p>I would like to stop threads generated in the following manner by using jToggleButton. The threads are used for watching folders for files. I tried a lot, and searched alot, but am not successful. Could any body help and suggest any solution to stop threads generated like. The threads are shown alive in Netbeans debugging even after pressing the jToggleButton.
  I have tried the volatile condition for stopping, 
  FYI: I have a jToggle button for starting and stopping the threads.</p>
  
  <p>The code is generated by Netbeans, so there is some extra code, but you may only focus on the code inside the jToggleActionListener and the code in another class: Thanks for your help.</p>
  
  <pre><code>package threadnames;
  
  import java.io.IOException;
  import java.nio.file.Path;
  import java.nio.file.Paths;
  import java.nio.file.StandardWatchEventKinds;
  import java.nio.file.WatchService;
  import java.util.concurrent.ExecutorService;
  import java.util.concurrent.Executors;
  import java.util.concurrent.TimeUnit;
  import java.util.logging.Level; 
  import java.util.logging.Logger;
  public class NewJFrame extends javax.swing.JFrame {
  
      public NewJFrame() {
          initComponents();
      }
      @SuppressWarnings("unchecked")
      // &lt;editor-fold defaultstate="collapsed" desc="Generated Code"&gt;                          
      private void initComponents() {
  
          jToggleButton1 = new javax.swing.JToggleButton();
  
          setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
  
      jToggleButton1.setText("Stop");
      jToggleButton1.addActionListener(new java.awt.event.ActionListener() {
          public void actionPerformed(java.awt.event.ActionEvent evt) {
              jToggleButton1ActionPerformed(evt);
          }
      });
  
      javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
      getContentPane().setLayout(layout);
      layout.setHorizontalGroup(
          layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addGroup(layout.createSequentialGroup()
              .addGap(84, 84, 84)
              .addComponent(jToggleButton1)
              .addContainerGap(142, Short.MAX_VALUE))
      );
      layout.setVerticalGroup(
          layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addGroup(layout.createSequentialGroup()
              .addGap(25, 25, 25)
              .addComponent(jToggleButton1)
              .addContainerGap(28, Short.MAX_VALUE))
      );
  
      pack();
  }// &lt;/editor-fold&gt;                        
  
  private void jToggleButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                               
      ExecutorService exec = Executors.newCachedThreadPool();
      if (this.jToggleButton1.isSelected()) {
          try {
              // TODO add your handling code here:
              Path home = Paths.get(System.getProperty("user.dir"));
              WatchService watcher;
  
              watcher = home.getFileSystem().newWatchService();
  
                  home.register(watcher, StandardWatchEventKinds.ENTRY_CREATE);
              Runnable task = new FileWatch(watcher);
              exec.submit(task);
              boolean terminated;
              terminated = exec.awaitTermination(1, TimeUnit.SECONDS);
  
              if (terminated) {
                  System.out.println("All tasks completed.");
              } else {
                  System.out.println("Some tasks are still running.");
              }
          } catch (IOException | InterruptedException ex) {
              Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
          }
      } else {
          exec.shutdownNow();
      }
  }                                              
  
  public static void main(String args[]) {
      try {
          for (javax.swing.UIManager.LookAndFeelInfo info    javax.swing.UIManager.getInstalledLookAndFeels()) {
              if ("Nimbus".equals(info.getName())) {
                  javax.swing.UIManager.setLookAndFeel(info.getClassName());
                  break;
  
  
              }
          }
      } catch (ClassNotFoundException | InstantiationException | IllegalAccessException |        javax.swing.UnsupportedLookAndFeelException ex) {
          java.util.logging.Logger.getLogger(NewJFrame.class
                  .getName()).log(java.util.logging.Level.SEVERE, null, ex);
      }
  
      java.awt.EventQueue.invokeLater(new Runnable() {
          public void run() {
              new NewJFrame().setVisible(true);
          }
      });
  }
  // Variables declaration - do not modify                     
  public javax.swing.JToggleButton jToggleButton1;
  // End of variables declaration                   
  }
  </code></pre>
  
  <p>Here is the other class for the run():</p>
  
  <pre><code>package threadnames;
  
  import java.nio.file.WatchEvent;
  import java.nio.file.WatchKey;
  import java.nio.file.WatchService;
  import java.nio.file.Watchable;
  
  final class FileWatch implements Runnable {
  
  private final WatchService watcher;
  
  FileWatch(WatchService watcher) {
      this.watcher = watcher;
  }
  
  @Override
  public void run() {
      while (!Thread.currentThread().isInterrupted()) {
          WatchKey key;
          try {
              key = watcher.take();
          } catch (InterruptedException ex) {
              Thread.currentThread().interrupt();
              break;
          }
          Watchable dir = key.watchable();
          System.out.println(dir);
          for (WatchEvent&lt;?&gt; evt : key.pollEvents()) {
              System.out.println("   " + evt.context());
          }
      }
  }
  }
  </code></pre>