Skip to content

Fall back to the WatchService watcher instead of polling on macOS - #16089

Merged
jdaugherty merged 6 commits into
apache:8.0.xfrom
codeconsole:fix/directory-watcher-fallback-8.0.x
Aug 5, 2026
Merged

jdaugherty merged 6 commits into
apache:8.0.xfrom
codeconsole:fix/directory-watcher-fallback-8.0.x

Conversation

@codeconsole

@codeconsole codeconsole commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor
2026-08-03T13:20:35.127-07:00  INFO 8719 --- [  restartedMain] [                                                 ] org.grails.io.watch.DirectoryWatcher     : Exception while trying to load WatchServiceDirectoryWatcher (this is probably Java 6 and WatchService isn't available). Falling back to PollingDirectoryWatcher.

java.lang.reflect.InvocationTargetException
        at org.grails.io.watch.DirectoryWatcher.<init>(DirectoryWatcher.java:62)
        at grails.boot.GrailsApp.enableDevelopmentModeWatch(GrailsApp.groovy:219)
        at grails.boot.GrailsApp.run(GrailsApp.groovy:122)
        at grails.boot.GrailsApp.run(GrailsApp.groovy:464)
        at grails.boot.GrailsApp.run(GrailsApp.groovy:453)
        at com.l3me.Application.main(Application.groovy:55)
Caused by: java.lang.NoClassDefFoundError: io/methvin/watchservice/MacOSXListeningWatchService
        at org.grails.io.watch.MacOsWatchServiceDirectoryWatcher.<init>(MacOsWatchServiceDirectoryWatcher.java:71)
        ... 6 common frames omitted
Caused by: java.lang.ClassNotFoundException: io.methvin.watchservice.MacOSXListeningWatchService
        ... 7 common frames omitted

Java 6 reference is pretty ancient

(this is probably Java 6 and WatchService isn't available)

Problem

DirectoryWatcher probes for JNA to decide whether the native macOS FSEvents watcher is usable:

Class.forName("com.sun.jna.Pointer");

JNA is not what that watcher needs. MacOsWatchServiceDirectoryWatcher 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 — org.testcontainers:testcontainers → com.github.docker-java:docker-java-transport-zerodep → net.java.dev.jna:jna is a common path. On macOS those applications are sent down a load of MacOsWatchServiceDirectoryWatcher that cannot succeed. The resulting NoClassDefFoundError is caught by a single catch-all that drops straight to PollingDirectoryWatcher, so they silently poll every watched directory on a 1s timer instead of receiving file system events:

Exception while trying to load WatchServiceDirectoryWatcher (this is probably Java 6
and WatchService isn't available). Falling back to PollingDirectoryWatcher.
Caused by: java.lang.NoClassDefFoundError: io/methvin/watchservice/MacOSXListeningWatchService

The fallback ordering makes this worse than having no JNA at all: without JNA the else branch selects WatchServiceDirectoryWatcher and 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 → JDK WatchService → 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 native WatchService there — FileSystems.getDefault().newWatchService() returns sun.nio.fs.PollingWatchService, and WatchServiceDirectoryWatcher registers 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. The ClassNotFoundException behind it stays at debug.

Verification

Selected delegate, comparing this branch against 8.0.x under three classpaths on macOS:

classpath before after
JNA present, directory-watcher absent PollingDirectoryWatcher WatchServiceDirectoryWatcher
neither present WatchServiceDirectoryWatcher unchanged
both present MacOsWatchServiceDirectoryWatcher unchanged

The broken case is fixed and both already-working cases are untouched.

DirectoryWatcherSpec covers 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 and directory-watcher absent, so JNA is added to the test runtime classpath.

:grails-bootstrap:test (145 tests), codeStyle and rat all pass.

Note

An alternative fix would be promoting io.methvin:directory-watcher to a real runtime dependency of grails-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.

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

codecov Bot commented Aug 3, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 47.36842% with 10 lines in your changes missing coverage. Please review.
✅ Project coverage is 52.3462%. Comparing base (6378d2d) to head (ab2b2af).
⚠️ Report is 2 commits behind head on 8.0.x.

Files with missing lines Patch % Lines
...n/groovy/org/grails/io/watch/DirectoryWatcher.java 47.3684% 9 Missing and 1 partial ⚠️
Additional details and impacted files

Impacted file tree graph

@@                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     
Files with missing lines Coverage Δ
...n/groovy/org/grails/io/watch/DirectoryWatcher.java 59.6491% <47.3684%> (+11.4348%) ⬆️

... and 7 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

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 jamesfredley left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't this be warn? Once you added the right library, doesn't this resolve itself?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@bito-code-review

Copy link
Copy Markdown

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.
@testlens-app

testlens-app Bot commented Aug 4, 2026

Copy link
Copy Markdown

✅ All tests passed ✅

🏷️ Commit: ab2b2af
▶️ Tests: 59064 executed
⚪️ Checks: 60/60 completed


Learn more about TestLens at testlens.app.

@codeconsole
codeconsole requested a review from jdaugherty August 4, 2026 22:04
@jdaugherty
jdaugherty merged commit 948775b into apache:8.0.x Aug 5, 2026
63 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

3 participants