Redis实现可重入锁

先说一下redis实现分布式锁的指令吧

> set lock:sixj true ex 5 nx
......do something......
> del lock:sixj

加锁的指令是setnx与expire组合的原子指令,key=lock:sixj,value=true,过期时间=5秒

redis分布式锁存在的问题:

​ 如果加锁和释放锁之间的逻辑执行时间超出了锁的超时时间,临界区的逻辑还没有执行完,另一个线程就会重新持有这把锁,导致临界区的代码不能严格控制串行执行。

言归正传,说redis可重入锁

所谓可重入锁就是一个锁支持同一个线程的多次加锁

使用线程的ThreadLocal变量存储当前线程持有锁的计数

public class RedisWithReentrantLock {
    private ThreadLocal<Map<String,Integer>> lockers = new ThreadLocal<>();
    private Jedis jedis;

    public RedisWithReentrantLock(Jedis jedis) {
        this.jedis = jedis;
    }
    private boolean _lock(String key){
        return jedis.set(key,"","nx","ex",5L) != null;
    }
    private void _unlock(String key){
        jedis.del(key);
    }
    private Map<String,Integer> currentLockers(){
        Map<String, Integer> refs = lockers.get();
        if(refs != null){
            return refs;
        }
        lockers.set(new HashMap<>());
        return lockers.get();
    }
    public boolean lock(String key){
        Map<String, Integer> refs = currentLockers();
        Integer refCnt = refs.get(key);
        if(refCnt != null){
            refs.put(key,refCnt+1);
            return true;
        }
        boolean ok = this._lock(key);
        if(! ok){
            return false;
        }
        refs.put(key,1);
        return true;
    }
    public boolean unlock(String key){
        Map<String, Integer> refs = currentLockers();
        Integer refCnt = refs.get(key);
        if(refCnt == null){
            return false;
        }
        refCnt -= 1;
        if(refCnt > 0){
            refs.put(key,refCnt);
        }else {
            refs.remove(key);
            this._unlock(key);
        }
        return true;
    }
}

测试:

RedisWithReentrantLock redis = new RedisWithReentrantLock(jedis);
System.out.println(redis.lock("sixj"));
System.out.println(redis.lock("sixj"));
System.out.println(redis.unlock("sixj"));
System.out.println(redis.unlock("sixj"));

运行结果:

true
true
true
true