Redisson分布式锁

redis是单线程为啥还有线程安全的问题?

redis不存在线程安全问题,问题在于客户端。比如clientA,clientB操作读和写的操作。key = 1,clientA + 1,clientB + 1,执行完毕理想结果key=3。然后这个结果是不能保证的。

key=1,执行顺序可能是这样的:
1. clientA getKey = 1
2. clientB getKey = 1
3. clientA setKey = 1 + 1 = 2
4. cleintB setKey = 1 + 1 = 2
执行结果可能就是key = 2,clientA和clientB都加一但最后的key有可能不等于3.

SetNX能解决这个并发问题吗?

set: 赋值
nx: 设置过期时间
setnx赋值和设置过期时间放在一个事务中,要么成功要么失败,这样获取锁是不是就能解决上面由于多个客户端所产生的的并发问题呢,答案是否定的。

clientA: setnx获取锁成功,锁已经过期了但clientA仍然在执行中。
clientB: setnx获取锁成功,这样就存在了并发问题了。

redisson来了

文档

获取锁

private void lock(long leaseTime, TimeUnit unit, boolean interruptibly) throws InterruptedException {
    long threadId = Thread.currentThread().getId();
    Long ttl = tryAcquire(-1, leaseTime, unit, threadId);
    // lock acquired
    if (ttl == null) {
        return;
    }

    RFuture<RedissonLockEntry> future = subscribe(threadId);
    if (interruptibly) {
        commandExecutor.syncSubscriptionInterrupted(future);
    } else {
        commandExecutor.syncSubscription(future);
    }

    try {
        while (true) {
            ttl = tryAcquire(-1, leaseTime, unit, threadId);
            // lock acquired
            if (ttl == null) {
                break;
            }

            // waiting for message
            if (ttl >= 0) {
                try {
                    future.getNow().getLatch().tryAcquire(ttl, TimeUnit.MILLISECONDS);
                } catch (InterruptedException e) {
                    if (interruptibly) {
                        throw e;
                    }
                    future.getNow().getLatch().tryAcquire(ttl, TimeUnit.MILLISECONDS);
                }
            } else {
                if (interruptibly) {
                    future.getNow().getLatch().acquire();
                } else {
                    future.getNow().getLatch().acquireUninterruptibly();
                }
            }
        }
    } finally {
        unsubscribe(future, threadId);
    }
//        get(lockAsync(leaseTime, unit));
}
  1. 尝试获取锁Long ttl = tryAcquire(-1, leaseTime, unit, threadId)
    执行获取锁命令:

  2. 获取锁成功,启动watch dog看门狗线程,会每隔10秒为持有的锁续命。
    scheduleExpirationRenewal(threadId)续命方法

  3. 获取锁失败,死循环尝试获取锁,直到获取锁成功。

  4. 释放锁

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

gzh-程序员灿灿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值