Repository navigation
Fall back to the WatchService watcher instead of polling on macOS - #16089
Conversation
DirectoryWatcher probed for JNA to decide whether the native macOS FSEvents watcher was usable. JNA is not what that watcher needs — it needs io.methvin:directory-watcher, which grails-bootstrap declares compileOnly and therefore never puts on an application's runtime classpath. Applications routinely acquire JNA transitively (Testcontainers -> docker-java-transport-zerodep -> jna is a common path), so on macOS they were sent down a load of MacOsWatchServiceDirectoryWatcher that could not succeed. The resulting NoClassDefFoundError was caught by a single catch-all that dropped straight to PollingDirectoryWatcher, so those applications silently polled every directory on a 1s timer instead of receiving file system events. The fallback ordering made this worse than having no JNA at all: without JNA the else branch selected WatchServiceDirectoryWatcher and worked correctly, so adding an unrelated dependency downgraded file watching. Probe for io.methvin.watchservice.MacOSXListeningWatchService, the class that actually backs the native watcher, and degrade in steps — native macOS, then the JDK WatchService, then polling. Polling is now only reached if the JDK cannot supply a WatchService, which cannot happen on the Java 21 baseline; the accompanying message no longer claims Java 6. Absence of the optional dependency is logged at debug rather than warn since it is an opt-in performance improvement, not a fault. DirectoryWatcherSpec covers the three outcomes and fails on the previous implementation. It needs JNA present and directory-watcher absent to reproduce the reported shape, so JNA is added to the test runtime.
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## 8.0.x #16089 +/- ##
==================================================
+ Coverage 52.3416% 52.3462% +0.0046%
- Complexity 18291 18298 +7
==================================================
Files 2036 2036
Lines 96346 96347 +1
Branches 16831 16829 -2
==================================================
+ Hits 50429 50434 +5
+ Misses 38492 38489 -3
+ Partials 7425 7424 -1
🚀 New features to boost your workflow:
|
Class.forName can raise NoClassDefFoundError rather than ClassNotFoundException when directory-watcher is present but the JNA it links against is not. That escaped createMacOsWatcher and prevented DirectoryWatcher from being constructed at all on macOS, which is worse than the polling downgrade this branch set out to fix. Catch LinkageError alongside ClassNotFoundException: a class that cannot be linked is as unusable as one that is absent, and both mean the JDK WatchService should be used instead. Rework the spec to cover the selection branches through observable behaviour rather than by reflecting over a private field. DirectoryWatcher gains a package-private accessor for the delegate it chose, and the cases that need io.methvin:directory-watcher are exercised by loading the watcher classes in class loaders assembled from a new resolvable optionalWatcher configuration, which deliberately does not join any compile or runtime classpath. That covers native selection, the linkage failure, the JNA-only classpath, the non-macOS path, and a functional test that starts a watcher and asserts a listener sees a modified file. Every selection case fails on the previous implementation, and the linkage case fails on the narrower catch it replaces.
The previous spec reached the chosen implementation through a package-private accessor added for that purpose, which conflicts with the project's requirement that tests exercise behaviour through the same APIs an application calls. Drop the accessor and assert what an application can actually observe: that a watched file's modification is reported. Selection is now pinned indirectly but precisely. A watcher that has been downgraded to polling only wakes every sleepTime, so setting a sleep interval far longer than the assertion timeout and still receiving the change proves the watcher is event driven — that case fails on the previous implementation, where a transitively acquired JNA sent macOS to PollingDirectoryWatcher. The optional-library cases construct and start the watcher in a class loader built from the optionalWatcher configuration, with JNA present or absent; reflection there only crosses the loader boundary, and every member it touches is public.
jamesfredley
left a comment
There was a problem hiding this comment.
We could backport to 7.x.x, since it has the same code.
Resolving the optional library is not enough to run it. MacOSXListeningWatchService
loads without a static initializer and its constructor touches no native
code, so spoofing os.name selects the native watcher on any platform.
CarbonAPI is not initialized until register is called, at which point
Native.loadLibrary("Carbon") fails anywhere but macOS — and that happens
inside addWatchDirectory, outside the fallbacks. The test would therefore
have failed on the Ubuntu and Windows CI legs.
The linkage test stays cross-platform: without JNA the probe fails before
any native registration, which is the behaviour it asserts.
| Class.forName("io.methvin.watchservice.MacOSXListeningWatchService"); | ||
| } catch (ClassNotFoundException | LinkageError e) { | ||
| if (LOG.isDebugEnabled()) { | ||
| LOG.debug("Native macOS file event watching is unavailable. Add 'io.methvin:directory-watcher' to the classpath for faster file watching.", e); |
There was a problem hiding this comment.
Shouldn't this be warn? Once you added the right library, doesn't this resolve itself?
There was a problem hiding this comment.
Agreed — changed to warn in ab2b2af.
Worth surfacing: the JDK supplies no native WatchService on macOS. FileSystems.getDefault().newWatchService() returns sun.nio.fs.PollingWatchService, and WatchServiceDirectoryWatcher registers without a sensitivity modifier, so the fallback polls at the default 10s. That is a real reload latency cost with a one dependency fix, so the message now states the consequence as well as naming the dependency — and yes, adding the library silences it.
The ClassNotFoundException stays at LOG.debug so the warn line remains a single actionable sentence rather than a stack trace, which is what made the message on 8.0.x noisy.
DirectoryWatcherSpec now also covers that the advice is emitted on macOS without the library, and that it stays off platforms it cannot help.
|
Changing the log level to warn is appropriate if the missing library is an optional dependency that does not prevent the application from functioning. If the library is required for the core functionality of the DirectoryWatcher, an error level is typically preferred to alert the user that the feature is unavailable. |
The JDK supplies no native WatchService on macOS — it is sun.nio.fs.PollingWatchService — so falling back to it costs real reload latency. Logging that at debug hid an actionable, one-dependency fix from the developers it affects. Warn instead, and keep the ClassNotFoundException itself at debug where it belongs. DirectoryWatcherSpec covers both that the advice is emitted on macOS without the optional library and that it stays off platforms it cannot help.
✅ All tests passed ✅🏷️ Commit: ab2b2af Learn more about TestLens at testlens.app. |
Java 6 reference is pretty ancient
Problem
DirectoryWatcherprobes for JNA to decide whether the native macOS FSEvents watcher is usable:JNA is not what that watcher needs.
MacOsWatchServiceDirectoryWatcherneedsio.methvin:directory-watcher, whichgrails-bootstrapdeclarescompileOnlyand therefore never puts on an application's runtime classpath.Applications routinely acquire JNA transitively —
org.testcontainers:testcontainers→com.github.docker-java:docker-java-transport-zerodep→net.java.dev.jna:jnais a common path. On macOS those applications are sent down a load ofMacOsWatchServiceDirectoryWatcherthat cannot succeed. The resultingNoClassDefFoundErroris caught by a single catch-all that drops straight toPollingDirectoryWatcher, so they silently poll every watched directory on a 1s timer instead of receiving file system events:The fallback ordering makes this worse than having no JNA at all: without JNA the
elsebranch selectsWatchServiceDirectoryWatcherand works correctly. Adding an unrelated dependency downgrades file watching.Change
Probe for
io.methvin.watchservice.MacOSXListeningWatchService— the class that actually backs the native watcher — and degrade in steps: native macOS → JDKWatchService→ polling.Polling is now only reached if the JDK cannot supply a
WatchService, which cannot happen on the Java 21 baseline. The message no longer claims Java 6. On macOS without the optional dependency the fallback is logged at warn: the JDK supplies no nativeWatchServicethere —FileSystems.getDefault().newWatchService()returnssun.nio.fs.PollingWatchService, andWatchServiceDirectoryWatcherregisters without a sensitivity modifier, so it polls at the default 10s — which is a real reload latency cost with a one dependency fix, and the message names it. TheClassNotFoundExceptionbehind it stays at debug.Verification
Selected delegate, comparing this branch against
8.0.xunder three classpaths on macOS:directory-watcherabsentPollingDirectoryWatcherWatchServiceDirectoryWatcherWatchServiceDirectoryWatcherMacOsWatchServiceDirectoryWatcherThe broken case is fixed and both already-working cases are untouched.
DirectoryWatcherSpeccovers the three outcomes and fails on the current implementation (2 of 3 cases). It also covers that the advice is emitted on macOS without the optional library and stays off platforms it cannot help. Reproducing the reported shape needs JNA present anddirectory-watcherabsent, so JNA is added to the test runtime classpath.:grails-bootstrap:test(145 tests),codeStyleandratall pass.Note
An alternative fix would be promoting
io.methvin:directory-watcherto a real runtime dependency ofgrails-bootstrap, giving every macOS application native watching. That adds JNA and a native library to all application classpaths, so I kept the dependency optional here and fixed only the selection logic. Happy to take that route instead if preferred.