Thread bug in FileAlterationMonitor#stop(int) (closes
Interrupt the thread created by FileAlterationMonitor on stop()
MODIFY
src/main/java/org/apache/commons/io/monitor/FileAlterationMonitor.java
src/main/java/org/apache/commons/io/monitor/FileAlterationMonitor.java
@@ -164,6 +164,7 @@ public synchronized void stop(final long stopInterval) throws Exception {
}
running = false;
try {
+ thread.interrupt();
thread.join(stopInterval);
} catch (final InterruptedException e) {
Thread.currentThread().interrupt();

MODIFY
src/test/java/org/apache/commons/io/monitor/FileAlterationMonitorTestCase.java
src/test/java/org/apache/commons/io/monitor/FileAlterationMonitorTestCase.java
import static org.junit.Assert.fail;
import java.io.File;
+import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.concurrent.Executors;
+import java.util.concurrent.ThreadFactory;
import org.apache.commons.io.testtools.TestUtils;
import org.junit.Test;
@@ -176,4 +178,38 @@ private void checkFile(final String label, final File file, final Collection<Fil
}
fail(label + " " + file + " not found");
}
+
+ /**
+ * Test case for IO-535
+ *
+ * Verify that {@link FileAlterationMonitor#stop()} stops the created thread
+ */
+ @Test
+ public void testStopWhileWaitingForNextInterval() throws Exception {
+ final Collection<Thread> createdThreads = new ArrayList<>(1);
+ final ThreadFactory threadFactory = new ThreadFactory() {
+ private final ThreadFactory delegate = Executors.defaultThreadFactory();
+
+ @Override
+ public Thread newThread(Runnable r) {
+ final Thread thread = delegate.newThread(r);
+ thread.setDaemon(true); //do not leak threads if the test fails
+ createdThreads.add(thread);
+ return thread;
+ }
+ };
+
+ final FileAlterationMonitor monitor = new FileAlterationMonitor(1_000);
+ monitor.setThreadFactory(threadFactory);
+
+ monitor.start();
+ assertFalse(createdThreads.isEmpty());
+
+ Thread.sleep(10); // wait until the watcher thread enters Thread.sleep()
+ monitor.stop(100);
+
+ for (Thread thread : createdThreads) {
+ assertFalse("The FileAlterationMonitor did not stop the threads it created.", thread.isAlive());
+ }
+ }
}

IO-535: Thread bug in FileAlterationMonitor#stop(int) (closes #58, #36)

Interrupt the thread created by FileAlterationMonitor on stop()