【无标题】

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);
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值