import java.io.IOException;
import java.nio.file.*;
import java.util.concurrent.TimeUnit;

public class Repro {
    public static void main(String[] args) throws IOException, InterruptedException {
        final Path root = Files.createTempDirectory("test");
        final Path foo = root.resolve("foo");
        final Path bar = root.resolve("bar");
        final Path baz = root.resolve("baz");

        Files.createDirectory(foo);
        Files.createDirectory(bar);
        Files.createDirectory(baz);

        final WatchService service = root.getFileSystem().newWatchService();
        final WatchKey fooKey = foo.register(service, StandardWatchEventKinds.ENTRY_CREATE);
        final WatchKey barKey = bar.register(service, StandardWatchEventKinds.ENTRY_CREATE);

        new Thread() {
            { setDaemon(true); }

            @Override
            public void run() {
                while (true) {
                    try {
                        final Path temp = Files.createTempFile(foo, "temp", ".tmp");
                        Files.delete(temp);
                        Thread.sleep(10);
                    } catch (IOException | InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }.start();

        new Thread() {
            { setDaemon(true); }

            @Override
            public void run() {
                while (true) {
                    try {
                        final WatchKey bazKey = baz.register(service, StandardWatchEventKinds.ENTRY_CREATE);
                        bazKey.cancel();
                        Thread.sleep(1);
                    } catch (IOException | InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }.start();

        while (true) {
            final WatchKey key = service.poll(60, TimeUnit.SECONDS);
            if (key == null) continue;

            System.out.println("Seen " + (key == fooKey ? "foo" : key == barKey ? "bar" : "???"));

            if (key == barKey) throw new IllegalStateException("Something is rotten in the state of Denmark");
            key.reset();
        }
    }
}
