LockFile.java
1.39 KB
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
42
43
44
45
46
47
48
package com.sitech.util;
import java.io.File;
import java.net.URI;
import java.util.Hashtable;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class LockFile extends File{
private static Hashtable<String , ReentrantReadWriteLock> locks = new Hashtable<String , ReentrantReadWriteLock>();
private ReentrantReadWriteLock lock = null;
public LockFile(File arg0, String arg1) {
super(arg0, arg1);
lock = initLock(this.getAbsolutePath());
}
public LockFile(String arg0, String arg1) {
super(arg0, arg1);
lock = initLock(this.getAbsolutePath());
}
public LockFile(String arg0) {
super(arg0);
lock = initLock(this.getAbsolutePath());
}
public LockFile(URI arg0) {
super(arg0);
lock = initLock(this.getAbsolutePath());
}
/*
* 这里要注意使用 static synchronized,不然可能同时有多个进行初始化这个文件
*/
private static synchronized ReentrantReadWriteLock initLock(String path) {
ReentrantReadWriteLock lock = locks.get(path);
if (lock == null) {
lock = new ReentrantReadWriteLock();
locks.put(path, lock);
}
return lock;
}
public ReentrantReadWriteLock getLock() {
return lock;
}
}