title: How to Kill a Watch Service Thread
body: <p>I have a requirement to watch a HotFolder based on request coming from my UI
  I have start and stops buttons on my UI, when I click on start my code should watch the folder and clicks on stop it should stop watching it. I am using watch service to watch HotFolder, I am passing flag from my controller to watch service to start and stop watching the folder. Please suggest me how can stop watching the folder?</p>
  
  <p>Here is the code snippets:</p>
  
  <pre><code>@RequestMapping(value = "/start", method = RequestMethod.GET)
  public ModelAndView hotFolder()
  {
      ModelAndView model = new ModelAndView();
      model.setViewName("welcomePage");
  
      HotFolder h = new HotFolder();
      h.hotfolderTesting(true);
      return model;
  } 
  
  @RequestMapping(value = "/stop", method = RequestMethod.POST)
  public ModelAndView hotFolderStop()
  {
      ModelAndView model = new ModelAndView();
      model.setViewName("welcomePage");
  
      HotFolder h = new HotFolder();
      h.hotfolderTesting(false);
      return model;
  }
  </code></pre>
  
  <p>HotFolder.java:</p>
  
  <pre><code>public void hotfolderTesting(boolean flag)
  {
      try (WatchService service = FileSystems.getDefault().newWatchService()) {
          Map&lt;WatchKey, Path&gt; keyMap = new HashMap&lt;&gt;();
          Path path = Paths.get("E:\\TestingWatch");
          keyMap.put(path.register(service, StandardWatchEventKinds.ENTRY_CREATE), path);
  
          WatchKey watchKey;
          if (flag) {
              while (true) {
                  watchKey = service.take();
                  for (WatchEvent&lt;?&gt; event : watchKey.pollEvents()) {
                      if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
                          System.out.println("Created: " + event.context());
                      } else if (event.kind() == StandardWatchEventKinds.ENTRY_DELETE) {
                          System.out.println("Deleted: " + event.context());
                      } else if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) {
                          System.out.println("Modified :" + event.context());
                      }
                  }
                  if (!watchKey.reset()) {
                      break;
                  }
              }
          }
      } catch (Exception ignored) {
      }
  }
  </code></pre>