架构(十三)动态本地锁

8 篇文章 1 订阅

一、引言

        加锁大家都知道,但是目前提供动态锁的基本都是分布式锁,根据订单或者某个收费款项进行加锁。比如这个1订单要收刷卡费用,那就OREDER_1做为key丢到redis进行分布式加锁。这也是当下分布式锁最流行的方式。

        但是对于平台项目或者一些并发程度低的场景,分布式锁就没有必要了,本地锁更加方便。但是本地锁只有synchronized、ReentrantLock之类的方式,想动态的加锁只用他们是实现不了的。

二、实现

        那么如果要实现动态的本地锁怎么做呢?

        先看看redis的分布式锁是怎么做的,他其实就是利用redis的单线程往里面存一个值,如果已经有线程存了,并发的线程就存不进去,只能等。只不过各个redis的客户端还要考虑删除的并发性、锁超时删除、加锁等待这些问题。

1、ConcurrentHashMap

        借鉴这个方案,本地也可以加个存储,为了并发的可读性使用ConcurrentHashMap,这里可以有效的避免其他线程解锁删除缓存

private static final ConcurrentHashMap<String, String> map = 
new ConcurrentHashMap<>();

        加锁就把OREDER_1塞到map里面塞的过程需要防止并发,所以使用synchronized之类的就可以,因为map塞数据可比业务执行的加锁时间短多了

private synchronized static boolean getLock(String key) {
        // map里面塞一下很快,可以使用synchronized
        if (map.containsKey(key)) {
            // 懒汉模式,再判断一遍,免得两个线程一起通过了外层的判断
            return false;
        }
        map.put(key,key);
        return true;
    }

        加锁的方法就是先判断一下有没有已经占了位置的,没有就往map里面占位置

public static boolean tryLock(String key, long timeout, TimeUnit unit) {
        if (map.containsKey(key)) {
            return false;
        }
        return getLock(key);
    }

        解锁就是直接删除

public static void unLock(String key) {
        if (!map.containsKey(key)) {
            return;
        }
        // 释放锁
        map.remove(key);
    }

        这是最简单的做法,那么上面的实现有什么问题呢?最大的问题就是删除的时候可能被其他线程给删了,毕竟不会所有人都按照预想的去使用工具,安全是架构应该考虑的。

        还有锁的超时、等待多长时间没有锁就失败两个功能点

2、优化解锁、锁超时

       要优化这个实现就可以结合ReentrantLock,他有判断是否本线程加锁和等待多长时间进行加锁的api,如果自己实现相当于把他里面的线程存储和睡眠唤醒给重复做一遍,没有必要。

        那么怎么用它呢,map的value存储一个lock,相当于一个key一个lock,生成和删除的时候可以使用synchronized,这个和刚刚说的一样,map里面塞一个删一个是很快的,new一个lock和lock.unlock也是很快的,主要的时间都在业务处理和同一场景下不同单号之间的阻塞

public class LockKeyUtil {

    private static final ConcurrentHashMap<String, ReentrantLock> map = new ConcurrentHashMap<>();

    /**
     * 从map里获取锁 如果存在则返回 不存在则创建
     *
     * @param key key
     */
    private synchronized static ReentrantLock getReentrantLock(String key) {
        if (map.containsKey(key)) {
            return map.get(key);
        }
        return map.compute(key, (k, lock) -> {
            lock = new ReentrantLock();
            return lock;
        });
    }

    /**
     * 
     * @param key
     * @param waitTimeout
     * @param unit
     * @return
     */
    public static boolean tryLock(String key, long waitTimeout, TimeUnit unit) {
        ReentrantLock lock = getReentrantLock(key);
        boolean res;
        try {
            res = lock.tryLock(waitTimeout, unit);
        } catch (InterruptedException e) {
            unLock(key);
            res = false;
        }
        return res;
    }

    /**
     * 释放锁
     *
     * @param key key
     */
    public static synchronized void unLock(String key) {
        if (!map.containsKey(key)) {
            return;
        }
        ReentrantLock lock = map.get(key);
        // 释放锁
        if (lock.isHeldByCurrentThread()) {
            lock.unlock();
            map.remove(key);
        }
    }

}

3、优化加锁队列

        上面的实现可以看到还有一个问题,如果在tryLock的时候,多个线程进入了,那么第一个线程解锁的时候把他移除map就有问题了,所以unlock还可以根据加锁队列优化一下

        通过getQueueLength知道有没有在等待加锁的线程,当然了这三行代码不是原子性的,所以是有可能刚刚取完队列还没删除map之前就有线程去加锁了,但是这种情况并发几率可以说是万分之一不到,可以不考虑

public synchronized static void unLock(String key) {
        if (!map.containsKey(key)) {
            return;
        }
        ReentrantLock lock = map.get(key);
        // 释放锁
        if (lock.isHeldByCurrentThread()) {
            int wait = lock.getQueueLength();
            lock.unlock();
            if (wait == 0) {
                map.remove(key);
            }
        }
    }

4、执行超时自动解锁

        这里还有一个执行超时自动解锁的功能,其实感觉没必要,用的时候一般都是在finally里面去unlock,所以几乎不会有不解锁的情况

String key = LOCK + request.getId();
        boolean locked = LockKeyUtil.tryLock(key, 3, TimeUnit.SECONDS);
        if (!locked) {
            throw new OrderException("LOCK_FAIL");
        }
        try {
            //业务处理
            
        } finally {
            LockKeyUtil.unLock(key);
        }

       

三、测试

1、相同key测试代码

        这段代码主要是让线程1或者3先拿到锁,那么其中一个和3就一定处于等待状态,如果是3在等,他到最后也抢不到锁

public static void main(String[] args) {
        String key = "order_1666";
        Thread thread1 = new Thread(() -> {
            LocalDateTime now = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String formattedDateTime = now.format(formatter);
            System.out.println("thread1:" + Thread.currentThread().getName() + " start:" + formattedDateTime);
            boolean res = LockKeyUtil.tryLock(key, 2, TimeUnit.SECONDS);
            System.out.println("thread1:" + Thread.currentThread().getName() + " lock res:" + res);
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            LockKeyUtil.unLock(key, true);
            now = LocalDateTime.now();
            formattedDateTime = now.format(formatter);
            System.out.println("thread1:" + Thread.currentThread().getName() + " end:" + formattedDateTime);
        });
        Thread thread2 = new Thread(() -> {
            try {
                Thread.sleep(1);
                LocalDateTime now = LocalDateTime.now();
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                String formattedDateTime = now.format(formatter);
                System.out.println("thread2:" + Thread.currentThread().getName() + " start:" + formattedDateTime);
                boolean res = LockKeyUtil.tryLock(key, 5, TimeUnit.SECONDS);
                System.out.println("thread2:" + Thread.currentThread().getName() + " lock res:" + res);
                Thread.sleep(5000);
                LockKeyUtil.unLock(key, true);
                now = LocalDateTime.now();
                formattedDateTime = now.format(formatter);
                System.out.println("thread2:" + Thread.currentThread().getName() + " end:" + formattedDateTime);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        Thread thread3 = new Thread(() -> {
            LocalDateTime now = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String formattedDateTime = now.format(formatter);
            System.out.println("thread3:" + Thread.currentThread().getName() + " start:" + formattedDateTime);
            boolean res = LockKeyUtil.tryLock(key, 1, TimeUnit.SECONDS);
            System.out.println("thread3:" + Thread.currentThread().getName() + " lock res:" + res);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            LockKeyUtil.unLock(key, true);
            now = LocalDateTime.now();
            formattedDateTime = now.format(formatter);
            System.out.println("thread3:" + Thread.currentThread().getName() + " end:" + formattedDateTime);
        });
        thread1.start();
        thread2.start();
        thread3.start();
    }

 

2、相同key测试结果

        结果和预期相符,线程1先抢到了,执行完之后线程2 抢到,线程3在过程中就失败了

        整个执行链路也给打出来了

thread1:Thread-0 start:2024-02-06 13:59:12
thread3:Thread-2 start:2024-02-06 13:59:12
thread2:Thread-1 start:2024-02-06 13:59:12
thread:Thread-0 tryLock key:order_1666 start
thread:Thread-2 tryLock key:order_1666 start
thread:Thread-1 tryLock key:order_1666 start
thread:Thread-0 getReentrantLock key:order_1666 start
thread:Thread-0 getReentrantLock key:order_1666 new ReentrantLock()
thread:Thread-1 getReentrantLock key:order_1666 start
thread:Thread-0 tryLock key:order_1666res:true
thread1:Thread-0 lock res:true
thread:Thread-1 getReentrantLock key:order_1666 containsKey
thread:Thread-2 getReentrantLock key:order_1666 start
thread:Thread-2 getReentrantLock key:order_1666 containsKey
thread:Thread-2 tryLock key:order_1666res:false
thread3:Thread-2 lock res:false
thread:Thread-0 unLock key:order_1666 unlock success
thread:Thread-2 unLock key:order_1666 not isHeldByCurrentThread
thread:Thread-1 tryLock key:order_1666res:true
thread2:Thread-1 lock res:true
thread1:Thread-0 end:2024-02-06 13:59:14
thread3:Thread-2 end:2024-02-06 13:59:14
thread:Thread-1 unLock key:order_1666 unlock success
thread:Thread-1 unLock key:order_1666 map remove
thread2:Thread-1 end:2024-02-06 13:59:19

3、不同key测试

        就是多加一个key去加锁解锁,看能不能同时加同时解        

public static void main(String[] args) {
        String key = "order_1666";
        Thread thread1 = new Thread(() -> {
            LocalDateTime now = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String formattedDateTime = now.format(formatter);
            System.out.println("thread1:" + Thread.currentThread().getName() + " start:" + formattedDateTime);
            boolean res = LockKeyUtil.tryLock(key, 2, TimeUnit.SECONDS);
            System.out.println("thread1:" + Thread.currentThread().getName() + " lock res:" + res);
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            LockKeyUtil.unLock(key, true);
            now = LocalDateTime.now();
            formattedDateTime = now.format(formatter);
            System.out.println("thread1:" + Thread.currentThread().getName() + " end:" + formattedDateTime);
        });
        Thread thread2 = new Thread(() -> {
            try {
                Thread.sleep(1);
                LocalDateTime now = LocalDateTime.now();
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                String formattedDateTime = now.format(formatter);
                System.out.println("thread2:" + Thread.currentThread().getName() + " start:" + formattedDateTime);
                boolean res = LockKeyUtil.tryLock(key, 5, TimeUnit.SECONDS);
                System.out.println("thread2:" + Thread.currentThread().getName() + " lock res:" + res);
                Thread.sleep(5000);
                LockKeyUtil.unLock(key, true);
                now = LocalDateTime.now();
                formattedDateTime = now.format(formatter);
                System.out.println("thread2:" + Thread.currentThread().getName() + " end:" + formattedDateTime);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        String key3 = "order_1999";
        Thread thread3 = new Thread(() -> {
            LocalDateTime now = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String formattedDateTime = now.format(formatter);
            System.out.println("thread3:" + Thread.currentThread().getName() + " start:" + formattedDateTime);
            boolean res = LockKeyUtil.tryLock(key3, 1, TimeUnit.SECONDS);
            System.out.println("thread3:" + Thread.currentThread().getName() + " lock res:" + res);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            LockKeyUtil.unLock(key3, true);
            now = LocalDateTime.now();
            formattedDateTime = now.format(formatter);
            System.out.println("thread3:" + Thread.currentThread().getName() + " end:" + formattedDateTime);
        });
        thread1.start();
        thread2.start();
        thread3.start();
    }

        结果是不同的key可以同时加锁的,这就实现了锁的动态性

thread2:Thread-1 start:2024-02-06 14:06:28
thread1:Thread-0 start:2024-02-06 14:06:28
thread3:Thread-2 start:2024-02-06 14:06:28
thread3:Thread-2 lock res:true
thread2:Thread-1 lock res:true
thread3:Thread-2 end:2024-02-06 14:06:29
thread1:Thread-0 lock res:false
thread1:Thread-0 end:2024-02-06 14:06:32
thread2:Thread-1 end:2024-02-06 14:06:33

四、总结        

        最后的实现就是这样了

f6d008a35cc144f89dec2df89714664d.png

        看起来很简单的功能,要考虑的东西其实很多,这种实现也不是唯一的,有兴趣可以跟作者讨论其他的实现方案

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

胖当当技术

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

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

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

打赏作者

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

抵扣说明:

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

余额充值