Created
September 7, 2016 07:03
-
-
Save kaedea/a65a8ef6e266aaf73dbdf2b3e487da5a to your computer and use it in GitHub Desktop.
Java process-safe locker
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
/** | |
* 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