fixing a race on SharedLockFile

This commit is contained in:
Clebert Suconic 2015-04-08 11:14:21 -04:00
parent f2837bac03
commit ab8f54b066
2 changed files with 35 additions and 5 deletions

View File

@ -44,7 +44,7 @@ public class SharedFileLocker extends AbstractLocker {
public void doStart() throws Exception { public void doStart() throws Exception {
if (lockFile == null) { if (lockFile == null) {
File lockFileName = new File(directory, "lock"); File lockFileName = new File(directory, "lock");
lockFile = new LockFile(lockFileName, true); lockFile = new LockFile(lockFileName, false);
if (failIfLocked) { if (failIfLocked) {
lockFile.lock(); lockFile.lock();
} else { } else {

View File

@ -45,8 +45,27 @@ public class SharedFileLockerTest
} }
@Test
public void testLoop() throws Exception
{
// Increase the number of iterations if you are debugging races
for (int i = 0 ; i < 100; i++)
{
internalLoop(5);
}
}
@Test @Test
public void testLogging() throws Exception public void testLogging() throws Exception
{
// using a bigger wait here
// to make sure we won't log any extra info
internalLoop(100);
}
private void internalLoop(long timewait) throws Exception
{ {
final AtomicInteger logCounts = new AtomicInteger(0); final AtomicInteger logCounts = new AtomicInteger(0);
DefaultTestAppender appender = new DefaultTestAppender() { DefaultTestAppender appender = new DefaultTestAppender() {
@ -76,8 +95,6 @@ public class SharedFileLockerTest
Assert.assertTrue(locker1.keepAlive()); Assert.assertTrue(locker1.keepAlive());
Thread.sleep(10);
thread = new Thread("Locker Thread") thread = new Thread("Locker Thread")
{ {
public void run() public void run()
@ -95,8 +112,21 @@ public class SharedFileLockerTest
thread.start(); thread.start();
// Waiting some small time here, you shouldn't see many messages // I need to make sure the info was already logged
Thread.sleep(100); // but I don't want to have an unecessary wait here,
// as I want the test to run as fast as possible
{
long timeout = System.currentTimeMillis() + 5000;
while (logCounts.get() < 1 && System.currentTimeMillis() < timeout)
{
Thread.sleep(1);
}
}
if (timewait > 0)
{
Thread.sleep(timewait);
}
Assert.assertTrue(thread.isAlive()); Assert.assertTrue(thread.isAlive());