java 本地程序锁的参考实现
public class LocalLockMgr {
/**
* 新建锁,独占
*/
private static final int NEW_LOCK = -1;
/**
* 删除锁,独占
*/
private static final int DELETE_LOCK = -2;
/**
* 使用锁, 共享、累加
*/
private static final int USE_LOCK = 1;
/**
* ConcurrentHashMap<key, lockNumber>
* 若 < 0 为独占锁,不可再锁. 若 > 0,为共享锁的数量.
*/
private static final ConcurrentHashMap<String, AtomicInteger> lockMap = new ConcurrentHashMap<>();
public static boolean isUseLock(int lock) {
return lock >= USE_LOCK;
}
/**
* 加使用锁
*
* @param key
* @return 若<0, 返回独占锁 ; 若>0,返回共享锁的数量
*/
public static int addUseLock(String key) {
AtomicInteger one = new AtomicInteger(USE_LOCK);
AtomicInteger old = lockMap.putIfAbsent(key, one);
if (old == null) {
return one.get();
} else {
synchronized (old) {
int count = old.get()
if (count < 0) {// 存在独占锁
return count;
} else {
return old.addAndGet(USE_LOCK);
}
}
}
}
public static void releaseUseLock(String key) {
releaseLock(key, USE_LOCK);
}
// new lock ...
public static boolean isNewLock(int lock) {
return lock == NEW_LOCK;
}
public static int addNewLock(String key) {
return addExclusiveLock(key, NEW_LOCK);
}
public static void releaseNewLock(String key) {
releaseLock(key, NEW_LOCK);
}
// delete lock
public static boolean isDeleteLock(int lock) {
return lock == DELETE_LOCK;
}
public static int addDeleteLock(String key) {
return addExclusiveLock(key, DELETE_LOCK);
}
public static void releaseDeleteLock(String key) {
releaseLock(key, DELETE_LOCK);
}
// add exclusive lock
private static int addExclusiveLock(String key, int exclusiveLock) {
AtomicInteger one = new AtomicInteger(exclusiveLock);
AtomicInteger old = lockMap.putIfAbsent(key, one);
if (old == null) {
return one.get();
} else {
synchronized (old) {
int count = old.get();
if (count != 0) {// 存在其它锁
return count;
} else {
return old.addAndGet(exclusiveLock);
}
}
}
}
// release lock
private static void releaseLock(String key, int lock) {
AtomicInteger locks = lockMap.get(key);
locks.addAndGet(-lock);
}
}