Skip to content

Instantly share code, notes, and snippets.

@holyjak
Last active December 23, 2015 12:19
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 holyjak/6634219 to your computer and use it in GitHub Desktop.
Save holyjak/6634219 to your computer and use it in GitHub Desktop.
Wonders of Code - Simplicity vs. Robustness In Lock File Handling (http://wp.me/p3ui6n-1k) - the robust re-design
public class RobustSingletonBatchJob {
// Note: We could use File.deleteOnExit() but the docs says it is not 100% reliable and recommends to
// use java.nio.channels.FileLock; however this code works well enough for us
static synchronized boolean getLock() {
File file = new File(LOCK_DIRECTORY, StaticConfiguration.getGroupPrefix());
try {
// Will try to create path to lockfile if it does not exist.
file.getParentFile().mkdirs(); // #1 Create the lock dir if it doesn't exist
if (file.createNewFile()) {
return true;
} else {
log.info("Lock file " + file.getAbsolutePath() + " already exists."); // #2 Helpful error msg w/ path
return false;
}
} catch (IOException e) {
throw new RuntimeException("Failed to create lock file " + file.getAbsolutePath()
+ " due to " + e + ". Fix the problem and retry."
, e); // #3 Helpful error message with context (file path)
}
}
private synchronized static void releaseLock() {
File file = new File(LOCK_DIRECTORY, StaticConfiguration.getGroupPrefix());
file.delete();
}
public static void main(String[] args) throws Exception {
boolean releaseLockUponCompletion = true;
try {
...
if (! getLock() {
releaseLockUponCompletion = false;
log.error("Lock file is present, exiting."); // Lock path already logged
throw new RuntimeException("Lock file is present"); // throwing is nicer than System.exit/return
}
... // do the job (may throw exceptions)
} finally {
if (releaseLockUponCompletion) {
releaseLock(); // #4 Always release the lock, even upon exceptions
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment