1

In Eclipse, a unit test fires up this code and when the watched file is altered, outputs the new text.

In Tomcat, it hangs where shown.

I've grovelled around online for quite some time trying to find anyone with a similar problem, but nothing showed up.

This is vanilla watcher code, and because it works fine in Eclipse, there must be a Tomcat-specific issue, but what?

The file is accessible to the code in Tomcat. It's not a permissions problem.

public class Foo extends Thread {
    File watchedFile = <the watched file>;
    WatchService watcher = FileSystems.getDefault().newWatchService();
    Path dir = watchedFile.getParentFile().toPath();
    dir.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY);

    @Override
    public void run() {
        while (true) {
            WatchKey key;
            try {
                key = watcher().take(); <<< HANGS HERE IN TOMCAT, DOESN'T HANG HERE IN ECLIPSE.
            } catch (InterruptedException | ClosedWatchServiceException e) {
                break;
            }
            try {
                for (WatchEvent<?> event : key.pollEvents()) {
                    WatchEvent.Kind<?> kind = event.kind();
                    if (kind == StandardWatchEventKinds.OVERFLOW) {
                        continue;
                    }
                    if (kind == StandardWatchEventKinds.ENTRY_MODIFY) {
                        WatchEvent<Path> pathEvent = (WatchEvent<Path>)event;
                        if (pathEvent.context().toString().equals(watchedFile.getName()) {
                            // Do something.
                        }
                    }
                }
            } catch (Exception e) {
                throw new RuntimeException("Trouble: " + e.getMessage(), e);
            }
            if (!key.reset()) {
                break;
            }
        }
    }
}

UPDATE: . The problem was that I was writing to the file from outside Docker, so the change event wasn’t seen.

It’s similar to Java WatchService not generating events while watching mapped drives.

Jim Showalter
  • 550
  • 3
  • 8
  • 20

0 Answers0