javawatchservice

How can i stop WatchService (java)


How can I stop the execution:

key = watchService.take()

my code:


//Watcher
public class DirectoryWatcherExample {

    public static void main(String[] args) throws IOException, InterruptedException {

        WatchService watchService = FileSystems.getDefault().newWatchService();
        //My folder
        Path path = Paths.get("D:\\java\\Input");
        
        path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);
        WatchKey key;
        while (((key = watchService.take()) != null)) {
            
            System.out.println(key);
            System.out.println(key.toString());
            
            for (WatchEvent<?> event : key.pollEvents()) {
                if(event.context().toString().contains(".dat")){
                
                    System.out.println("FileName: "+event.context());
            
                }
            }
            key.reset();
        }

        watchService.close();
    }

}

my code is waiting for the execution of that line, is it possible to somehow stop the execution, tried:

 key.cancel();
 watchService.close()

but this did not give any result, can you tell me how to solve this problem?


Solution

  • The take() method of java.nio.WatchService is defined to wait undeterminedly until a watched-for event occurs. So there is no way to "stop" it.

    If you do not want to wait for an undetermined time, you can use poll(), which returns immediately, or poll(long timeout, TimeUnit unit) which returns after the specified time or when an event occurs, whatever happens first.

    The most 'natural' place to run such a watcher service would be a background thread, so that the program can proceed while the watcher is waiting for the seeked event. The Callable/Future classes make a good candidate to use here. When the watcher is running in a Thread or Future, the main program could "stop" it by using Thread.interrupt() or Future.cancel().

    And be sure to join or daemonize the threads you create, otherwise your program will not finish.