forked from pquiring/javaforce
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJFLockFile.java
More file actions
executable file
·41 lines (36 loc) · 914 Bytes
/
Copy pathJFLockFile.java
File metadata and controls
executable file
·41 lines (36 loc) · 914 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package javaforce;
/** File Locking object.
*
* @author pquiring
*/
import java.io.*;
import java.nio.channels.*;
public class JFLockFile {
private RandomAccessFile lockraf; // The file we'll lock
private FileChannel lockChannel; // The channel to the file
private FileLock lockLock; // The lock object we hold
private File lockFile;
public boolean lock(String fileName) {
try {
lockFile = new File(fileName);
lockraf = new RandomAccessFile(lockFile, "rw");
lockChannel = lockraf.getChannel();
lockLock = lockChannel.tryLock();
if (lockLock == null) return false;
} catch (Exception e) {
JFLog.log(e);
return false;
}
return true;
}
public void unlock() {
if (lockLock == null) return;
try {
lockLock.release();
lockraf.close();
lockFile.delete();
} catch (Exception e) {
JFLog.log(e);
}
}
}