import java.nio.file.*;
import static java.nio.file.StandardWatchEventKinds.*;

sbool testJDKWatchService() {
  ret recordSuccessOrFailure('testJDKWatchService, testJDKWatchService_noLog());
};

sbool testJDKWatchService_noLog() false on exception {
  final File dir = mkdirs(createTempDir());
  final Path path = dir.toPath();
  
  final WatchService watchService = FileSystems.getDefault().newWatchService();
  final WatchKey watchKey = path.register(watchService, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY, OVERFLOW);
  
  final Set<S> changes = synchroSet();
  thread {
    try {
      saveTextFile(newFile(dir, "bla"), "1");
      Countdown countdown = fiveSeconds();
      while (l(changes) < 2 && !countdown.done())
        sleep(1);
    } finally {
      watchService.close();
    }
  }
  
  final Countdown countdown = fiveSeconds();
  expectException(ClosedWatchServiceException.class, r {
    while (!countdown.done()) {
      final WatchKey wk = watchService.take();

      for (WatchEvent<?> event : wk.pollEvents()) pcall {
        final Path changed = (Path) event.context();
        print("Changed: " + changed + ", " + event.kind());
        changes.add(changed.toFile().getName());
      }
      
      wk.reset();
    }
  });
    
  pcall { watchService.close(); }
  deleteDirectory(dir);
  ret eq(changes, lithashset("bla", "bla_temp"));
  
}