Skip to content

Commit a4705cc

Browse files
SvetlinZarevPascalSchumacher
authored andcommitted
IO-535: Thread bug in FileAlterationMonitor#stop(int) (closes #58, #36)
Interrupt the thread created by FileAlterationMonitor on stop()
1 parent e9eb2d8 commit a4705cc

2 files changed

Lines changed: 37 additions & 0 deletions

File tree

src/main/java/org/apache/commons/io/monitor/FileAlterationMonitor.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,7 @@ public synchronized void stop(final long stopInterval) throws Exception {
164164
}
165165
running = false;
166166
try {
167+
thread.interrupt();
167168
thread.join(stopInterval);
168169
} catch (final InterruptedException e) {
169170
Thread.currentThread().interrupt();

src/test/java/org/apache/commons/io/monitor/FileAlterationMonitorTestCase.java

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,11 @@
2222
import static org.junit.Assert.fail;
2323

2424
import java.io.File;
25+
import java.util.ArrayList;
2526
import java.util.Collection;
2627
import java.util.Iterator;
2728
import java.util.concurrent.Executors;
29+
import java.util.concurrent.ThreadFactory;
2830

2931
import org.apache.commons.io.testtools.TestUtils;
3032
import org.junit.Test;
@@ -176,4 +178,38 @@ private void checkFile(final String label, final File file, final Collection<Fil
176178
}
177179
fail(label + " " + file + " not found");
178180
}
181+
182+
/**
183+
* Test case for IO-535
184+
*
185+
* Verify that {@link FileAlterationMonitor#stop()} stops the created thread
186+
*/
187+
@Test
188+
public void testStopWhileWaitingForNextInterval() throws Exception {
189+
final Collection<Thread> createdThreads = new ArrayList<>(1);
190+
final ThreadFactory threadFactory = new ThreadFactory() {
191+
private final ThreadFactory delegate = Executors.defaultThreadFactory();
192+
193+
@Override
194+
public Thread newThread(Runnable r) {
195+
final Thread thread = delegate.newThread(r);
196+
thread.setDaemon(true); //do not leak threads if the test fails
197+
createdThreads.add(thread);
198+
return thread;
199+
}
200+
};
201+
202+
final FileAlterationMonitor monitor = new FileAlterationMonitor(1_000);
203+
monitor.setThreadFactory(threadFactory);
204+
205+
monitor.start();
206+
assertFalse(createdThreads.isEmpty());
207+
208+
Thread.sleep(10); // wait until the watcher thread enters Thread.sleep()
209+
monitor.stop(100);
210+
211+
for (Thread thread : createdThreads) {
212+
assertFalse("The FileAlterationMonitor did not stop the threads it created.", thread.isAlive());
213+
}
214+
}
179215
}

0 commit comments

Comments
 (0)