This is an automated email from the ASF dual-hosted git repository.

lukaszlenart pushed a commit to branch feat/WW-5864-struts-maven-plugin-watch
in repository https://gitbox.apache.org/repos/asf/struts.git

commit d40f83950b896496f9eb034522195401be963a4e
Author: Lukasz Lenart <[email protected]>
AuthorDate: Sat Nov 14 09:25:49 2026 +0100

    WW-5864 fix(tools): one reported background watcher per output directory
    
    A Throwable escaping the background watcher is logged before the thread
    ends, and a second bound execution in the same JVM for the same output
    directory logs that a watcher is already running and returns.
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
 .../org/apache/struts2/maven/watch/WatchMojo.java  | 74 ++++++++++++++++++----
 .../apache/struts2/maven/watch/WatchMojoTest.java  | 68 ++++++++++++++++++++
 2 files changed, 129 insertions(+), 13 deletions(-)

diff --git 
a/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/WatchMojo.java
 
b/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/WatchMojo.java
index fc73a4828..8843bb2df 100644
--- 
a/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/WatchMojo.java
+++ 
b/tools/struts-maven-plugin/src/main/java/org/apache/struts2/maven/watch/WatchMojo.java
@@ -34,6 +34,8 @@ import java.nio.file.Path;
 import java.time.Duration;
 import java.util.List;
 import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
 import java.util.function.BiConsumer;
 import java.util.function.BooleanSupplier;
 import java.util.function.Function;
@@ -44,6 +46,8 @@ public class WatchMojo extends AbstractMojo {
     static final String MULTI_MODULE_MESSAGE =
             "struts:watch supports a single module; run it in the module that 
owns the resources, e.g. -pl <module>";
 
+    private static final Set<Path> BACKGROUND_WATCHERS = 
ConcurrentHashMap.newKeySet();
+
     /**
      * Milliseconds between scans of the resource directories.
      */
@@ -86,8 +90,40 @@ public class WatchMojo extends AbstractMojo {
         }
         checkSingleModule();
 
-        Path basedir = project.getBasedir().toPath();
         Path outputDirectory = new 
File(project.getBuild().getOutputDirectory()).toPath();
+        if (background) {
+            watchInBackground(outputDirectory);
+            return;
+        }
+        ResourceWatcher watcher = prepareWatcher(outputDirectory);
+        getLog().info("Watching " + project.getResources().size() + " resource 
root(s); press Ctrl+C to stop");
+        long deadline = timeout > 0 ? System.nanoTime() + 
Duration.ofSeconds(timeout).toNanos() : 0;
+        BooleanSupplier keepRunning = () -> deadline == 0 || System.nanoTime() 
- deadline < 0;
+        watcher.run(Duration.ofMillis(pollInterval), keepRunning);
+    }
+
+    private void watchInBackground(Path outputDirectory) {
+        if (!claimBackgroundWatcher(outputDirectory)) {
+            getLog().info("struts:watch is already watching " + 
outputDirectory + " in this JVM; not starting another");
+            return;
+        }
+        try {
+            ResourceWatcher watcher = prepareWatcher(outputDirectory);
+            Duration interval = Duration.ofMillis(pollInterval);
+            Runnable task = backgroundTask(() -> watcher.run(interval, () -> 
true), outputDirectory,
+                    (message, e) -> getLog().error(message, e));
+            Thread thread = new Thread(task, "struts-watch");
+            thread.setDaemon(true);
+            thread.start();
+        } catch (RuntimeException | Error e) {
+            releaseBackgroundWatcher(outputDirectory);
+            throw e;
+        }
+        getLog().info("Watching " + project.getResources().size() + " resource 
root(s) in the background");
+    }
+
+    private ResourceWatcher prepareWatcher(Path outputDirectory) {
+        Path basedir = project.getBasedir().toPath();
         for (String warning : new 
StrutsReloadInspector(outputDirectory).warnings()) {
             getLog().warn(warning);
         }
@@ -114,19 +150,31 @@ public class WatchMojo extends AbstractMojo {
         ResourceWatcher watcher = new ResourceWatcher(scanner, pusher, 
filterFiles,
                 message -> getLog().debug(message), (message, e) -> 
getLog().error(message, e));
         watcher.start();
+        return watcher;
+    }
 
-        Duration interval = Duration.ofMillis(pollInterval);
-        if (background) {
-            Thread thread = new Thread(() -> watcher.run(interval, () -> 
true), "struts-watch");
-            thread.setDaemon(true);
-            thread.start();
-            getLog().info("Watching " + roots.size() + " resource root(s) in 
the background");
-            return;
-        }
-        getLog().info("Watching " + roots.size() + " resource root(s); press 
Ctrl+C to stop");
-        long deadline = timeout > 0 ? System.nanoTime() + 
Duration.ofSeconds(timeout).toNanos() : 0;
-        BooleanSupplier keepRunning = () -> deadline == 0 || System.nanoTime() 
- deadline < 0;
-        watcher.run(interval, keepRunning);
+    static boolean claimBackgroundWatcher(Path outputDirectory) {
+        return BACKGROUND_WATCHERS.add(registryKey(outputDirectory));
+    }
+
+    static void releaseBackgroundWatcher(Path outputDirectory) {
+        BACKGROUND_WATCHERS.remove(registryKey(outputDirectory));
+    }
+
+    private static Path registryKey(Path outputDirectory) {
+        return outputDirectory.toAbsolutePath().normalize();
+    }
+
+    static Runnable backgroundTask(Runnable work, Path outputDirectory, 
BiConsumer<String, Throwable> error) {
+        return () -> {
+            try {
+                work.run();
+            } catch (Throwable e) {
+                error.accept("struts:watch background watcher for " + 
outputDirectory + " stopped", e);
+            } finally {
+                releaseBackgroundWatcher(outputDirectory);
+            }
+        };
     }
 
     boolean shouldRun() {
diff --git 
a/tools/struts-maven-plugin/src/test/java/org/apache/struts2/maven/watch/WatchMojoTest.java
 
b/tools/struts-maven-plugin/src/test/java/org/apache/struts2/maven/watch/WatchMojoTest.java
index 5523c8408..83b04868e 100644
--- 
a/tools/struts-maven-plugin/src/test/java/org/apache/struts2/maven/watch/WatchMojoTest.java
+++ 
b/tools/struts-maven-plugin/src/test/java/org/apache/struts2/maven/watch/WatchMojoTest.java
@@ -20,10 +20,12 @@ package org.apache.struts2.maven.watch;
 
 import org.apache.maven.execution.MavenSession;
 import org.apache.maven.plugin.MojoFailureException;
+import org.apache.maven.plugin.logging.Log;
 import org.apache.maven.project.MavenProject;
 import org.junit.Rule;
 import org.junit.Test;
 import org.junit.rules.TemporaryFolder;
+import org.mockito.ArgumentCaptor;
 
 import java.io.File;
 import java.nio.file.Files;
@@ -35,7 +37,10 @@ import java.util.Map;
 
 import static org.assertj.core.api.Assertions.assertThat;
 import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
 public class WatchMojoTest {
@@ -139,6 +144,69 @@ public class WatchMojoTest {
         assertThat(errors).containsExactly("Failed to push bad.txt");
     }
 
+    @Test
+    public void secondBackgroundWatcherForTheSameOutputDirectoryIsRefused() 
throws Exception {
+        Path out = temp.newFolder("claimed").toPath();
+        Path other = temp.newFolder("other").toPath();
+        try {
+            assertThat(WatchMojo.claimBackgroundWatcher(out)).isTrue();
+            
assertThat(WatchMojo.claimBackgroundWatcher(out.resolve("x").resolve(".."))).isFalse();
+            assertThat(WatchMojo.claimBackgroundWatcher(other)).isTrue();
+
+            WatchMojo.releaseBackgroundWatcher(out);
+
+            assertThat(WatchMojo.claimBackgroundWatcher(out)).isTrue();
+        } finally {
+            WatchMojo.releaseBackgroundWatcher(out);
+            WatchMojo.releaseBackgroundWatcher(other);
+        }
+    }
+
+    @Test
+    public void 
boundExecutionReturnsWhenAWatcherAlreadyRunsForTheOutputDirectory() throws 
Exception {
+        Path out = temp.newFolder("running").toPath();
+        WatchMojo mojo = new WatchMojo();
+        mojo.background = true;
+        mojo.enabled = true;
+        MavenSession session = mock(MavenSession.class);
+        when(session.getProjects()).thenReturn(List.of(new MavenProject()));
+        mojo.session = session;
+        mojo.project = new MavenProject();
+        mojo.project.getBuild().setOutputDirectory(out.toString());
+        Log log = mock(Log.class);
+        mojo.setLog(log);
+        WatchMojo.claimBackgroundWatcher(out);
+        try {
+            mojo.execute();
+        } finally {
+            WatchMojo.releaseBackgroundWatcher(out);
+        }
+
+        ArgumentCaptor<CharSequence> info = 
ArgumentCaptor.forClass(CharSequence.class);
+        verify(log).info(info.capture());
+        assertThat(info.getValue().toString()).contains("already watching");
+        verify(log, never()).warn(any(CharSequence.class));
+    }
+
+    @Test
+    public void backgroundTaskReportsEscapingThrowableAndReleasesItsClaim() 
throws Exception {
+        Path out = temp.newFolder("dying").toPath();
+        List<Throwable> reported = new ArrayList<>();
+        Error failure = new LinkageError("boom");
+        WatchMojo.claimBackgroundWatcher(out);
+
+        WatchMojo.backgroundTask(() -> {
+            throw failure;
+        }, out, (message, e) -> reported.add(e)).run();
+
+        assertThat(reported).containsExactly(failure);
+        try {
+            assertThat(WatchMojo.claimBackgroundWatcher(out)).isTrue();
+        } finally {
+            WatchMojo.releaseBackgroundWatcher(out);
+        }
+    }
+
     private File write(Path path, long lastModified) throws Exception {
         Files.writeString(path, "x");
         File file = path.toFile();

Reply via email to