ReentrantLock再ロック可能


リエントラント性とは、スレッドがロックを保持している場合に再びロックを要求することであり、1つのロックが同じスレッドの複数回のロックをサポートしている場合、このロックはリエント可能である.例えばJava言語にReentrantLockがあるのは再ロック可能です.Redis分散ロックが再読み込みをサポートする場合は、スレッドのThreadlocal変数を使用して現在ロックを保持しているカウントを格納するクライアントのsetメソッドをパッケージする必要があります.
コードは次のとおりです.
public class RedisWithReentrantLock {

    private ThreadLocal> 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 currentLockers(){
        Map refs = lockers.get();
        if (null != refs){
            return refs;
        }
        lockers.set(new HashMap<>());
        return lockers.get();
    }

    public boolean lock(String key){
        Map refs = currentLockers();
        Integer refCnt = refs.get(key);
        if (null != refCnt){
            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 refs = currentLockers();
        Integer refCnt = refs.get(key);
        if (null ==  refCnt){
            return false;
        }
        refCnt -= 1;
        if (refCnt > 0){
            refs.put(key, refCnt);
        }else {
            refs.remove(key);
            this._lock(key);
        }
        return true;
    }

    /**
    public static void main(String[] args) {
        Jedis jedis = new Jedis("localhost");
        RedisWithReentrantLock redisWithReentrantLock = new RedisWithReentrantLock(jedis);
        System.out.println(redisWithReentrantLock.lock("TestLock"));
        System.out.println(redisWithReentrantLock.lock("TestLock"));
        System.out.println(redisWithReentrantLock.unlock("TestLock"));
        System.out.println(redisWithReentrantLock.unlock("TestLock"));
    }
    **/
     
}