Last active
December 30, 2015 12:59
-
-
Save jbialobr/7832503 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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