Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@kaedea
Created September 7, 2016 07:03
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 kaedea/a65a8ef6e266aaf73dbdf2b3e487da5a to your computer and use it in GitHub Desktop.
Save kaedea/a65a8ef6e266aaf73dbdf2b3e487da5a to your computer and use it in GitHub Desktop.
Java process-safe locker
/**
* Multi-process lock
*
* @author kaede
* @version date 16/9/6
*/
class Locker {
public static final int EXPIRED_TIME = 30 * 60 * 1000; // 30 minutes
final File lockFile;
public Locker(@NonNull String path) {
lockFile = new File(path);
}
public boolean tryLock() {
boolean mkdir = lockFile.mkdirs();
boolean expired = isExpired();
return mkdir || expired;
}
public void release() {
FileUtils.deleteQuietly(lockFile);
}
public boolean isExpired() {
long interval = System.currentTimeMillis() - lockFile.lastModified();
return interval > EXPIRED_TIME;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment