Skip to content

Instantly share code, notes, and snippets.

@raymyers
Created March 1, 2020 21:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raymyers/40a020c8824246a77a85fd548218030c to your computer and use it in GitHub Desktop.
Save raymyers/40a020c8824246a77a85fd548218030c to your computer and use it in GitHub Desktop.
Delete old Lucene write.lock file
import java.io.File;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LockCleaner {
private static final Logger logger = LoggerFactory.getLogger(LockCleaner.class);
public void clearOldLockInLuceneIndexDir(File indexDir) {
/* Used to recover from crashes. Deleting the lock file is normally an administrative action.
We are assuming here that if a lock is over an hour old, the process that initially took it has died
and deleting it is safe.
More context here. https://stackoverflow.com/questions/43011020/how-to-clear-the-lock-for-lucene-write-lock-file-after-a-jvm-crash
*/
try {
File lockFile = new File(indexDir, "write.lock");
long oneMinuteInMillis = 1000 * 60;
long oneHourInMillis = 60 * oneMinuteInMillis;
Date oneHourAgo = new Date(System.currentTimeMillis() - oneHourInMillis);
if (isFileOlderThan(lockFile, oneHourAgo)) {
log.warn("Found lock file in " + indexDir + " over an hour old, deleting");
deleteQuietly(lockFile);
}
} catch (Exception e) {
log.error("Error checking for old lock file.", e);
}
}
private static boolean isFileOlderThan(File file, Date threshold) {
return file.exists() && file.lastModified() < threshold.getTime();
}
private static boolean deleteQuietly(File file) {
try {
return file.delete();
} catch (final Exception ignored) {
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment