Skip to content

Instantly share code, notes, and snippets.

@jbialobr
Last active December 30, 2015 12:59
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 jbialobr/7832503 to your computer and use it in GitHub Desktop.
Save jbialobr/7832503 to your computer and use it in GitHub Desktop.
import java.io.File;
import java.io.IOException;
public class RobustSingletonBatchJob {
public static void main(String[] args) throws Exception
{
try(FileLock lock = new FileLock(new File("dir", "file")))
{
if (lock.isOwnsLock())
{
// ... // do the job (may throw exceptions)
}
}
}
public static class FileLock implements AutoCloseable
{
private File file;
private boolean ownsLock = false;
public FileLock(File file)
{
super();
this.file = file;
tryLock();
}
@Override
public void close()
{
unLock();
}
public boolean isOwnsLock()
{
return ownsLock;
}
private void tryLock()
{
try
{
if (!ownsLock)
{
file.getParentFile().mkdirs(); // #1 Create the lock dir if
// it doesn't exist
if (file.createNewFile())
{
ownsLock = true;
}
}
}
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 void unLock()
{
if (ownsLock)
{
file.delete();
ownsLock = false;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment