架构(十三)动态本地锁

一、引言

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

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

二、实现

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

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

1、ConcurrentHashMap

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

java 复制代码
private static final ConcurrentHashMap<String, String> map = 
new ConcurrentHashMap<>();

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

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

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

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

解锁就是直接删除

java 复制代码
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也是很快的,主要的时间都在业务处理和同一场景下不同单号之间的阻塞

java 复制代码
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之前就有线程去加锁了,但是这种情况并发几率可以说是万分之一不到,可以不考虑

java 复制代码
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,所以几乎不会有不解锁的情况

java 复制代码
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在等,他到最后也抢不到锁

java 复制代码
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在过程中就失败了

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

java 复制代码
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去加锁解锁,看能不能同时加同时解

java 复制代码
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可以同时加锁的,这就实现了锁的动态性

java 复制代码
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

四、总结

最后的实现就是这样了

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

相关推荐
2402_8575893621 分钟前
“衣依”服装销售平台:Spring Boot框架的设计与实现
java·spring boot·后端
吾爱星辰1 小时前
Kotlin 处理字符串和正则表达式(二十一)
java·开发语言·jvm·正则表达式·kotlin
哎呦没1 小时前
大学生就业招聘:Spring Boot系统的架构分析
java·spring boot·后端
_.Switch2 小时前
Python Web 应用中的 API 网关集成与优化
开发语言·前端·后端·python·架构·log4j
编程、小哥哥2 小时前
netty之Netty与SpringBoot整合
java·spring boot·spring
IT学长编程3 小时前
计算机毕业设计 玩具租赁系统的设计与实现 Java实战项目 附源码+文档+视频讲解
java·spring boot·毕业设计·课程设计·毕业论文·计算机毕业设计选题·玩具租赁系统
韩楚风3 小时前
【linux 多进程并发】linux进程状态与生命周期各阶段转换,进程状态查看分析,助力高性能优化
linux·服务器·性能优化·架构·gnu
莹雨潇潇3 小时前
Docker 快速入门(Ubuntu版)
java·前端·docker·容器
杨哥带你写代码3 小时前
足球青训俱乐部管理:Spring Boot技术驱动
java·spring boot·后端
郭二哈4 小时前
C++——模板进阶、继承
java·服务器·c++