JAVA细粒度、互斥KEY锁 —— KeyLock

本文介绍了一种基于KEY的细粒度互斥锁KeyLock的设计与实现,该锁能够提高高并发场景下的线程并行度。通过转账场景演示了KeyLock如何减少线程间的竞争,提高程序执行效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文地址:http://blog.youkuaiyun.com/icebamboo_moyun/article/details/9391915

参考:http://bbs.youkuaiyun.com/topics/390523873

java中的几种锁:synchronized,ReentrantLock,ReentrantReadWriteLock已基本可以满足编程需求,但其粒度都太大,同一时刻只有一个线程能进入同步块,这对于某些高并发的场景并不适用。本文实现了一个基于KEY(主键)的互斥锁,具有更细的粒度,在缓存或其他基于KEY的场景中有很大的用处。下面将讲解这个锁的设计和实现

(关于这个锁的讨论贴:KeyLock讨论贴-优快云


设想这么一个场景:转账

[java]  view plain copy
  1. private int[] accounts; // 账户数组,其索引为账户ID,内容为金额  
  2.   
  3. public boolean transfer(int from, int to, int money) {  
  4.     if (accounts[from] < money)  
  5.         return false;  
  6.     accounts[from] -= money;  
  7.     accounts[to] += money;  
  8.     return true;  
  9. }  

从from中转出金额到to中。可能同时会有很多个线程同时调用这个转账方法,为保证原子性,保证金额不会出错,必须为这个方法加个锁,防止对共享变量accounts的并发修改。

加锁后的代码如下:

[java]  view plain copy
  1. private int[] accounts; // 账户数组,其索引为账户ID,内容为金额  
  2. private Lock lock = new ReentrantLock();  
  3.   
  4. public boolean transfer(int from, int to, int money) {  
  5.     lock.lock();  
  6.     try {  
  7.         if (accounts[from] < money)  
  8.             return false;  
  9.         accounts[from] -= money;  
  10.         accounts[to] += money;  
  11.         return true;  
  12.     } finally {  
  13.         lock.unlock();  
  14.     }  
  15. }  


好了,加锁后这个代码就能保证金额不出错了。但问题又出现了,一次只能执行一个转账过程!意思就是A给B转账的时候,C要给D转账也得等A给B转完了才能开始转。这就有点扯蛋了,就像只有一个柜台,所有人必须排队等前面的处理完了才能到自己,效率太低。

解决这种情况有一个方案:A给B转账的时候只锁定A和B的账户,使其转账期间不能再有其他针对A和B账户的操作,但其他账户的操作可以并行发生。类似于如下场景:

[java]  view plain copy
  1. public boolean transfer(int from, int to, int money) {  
  2.     lock.lock(from, to);  
  3.     try {  
  4.         if (accounts[from] < money)  
  5.             return false;  
  6.         accounts[from] -= money;  
  7.         accounts[to] += money;  
  8.         return true;  
  9.     } finally {  
  10.         lock.unlock(from, to);  
  11.     }  
  12. }  


但很显然,JAVA并没有为我们提供这样的锁(也有可能是我没找到。。。)

于是,就在这样的需求下我花了整一天来实现了这个锁——KeyLock(代码量很短,但多线程的东西真的很让人头疼)

不同于synchronized等锁,KeyLock是对所需处理的数据的KEY(主键)进行加锁,只要是对不同key操作,其就可以并行处理,大大提高了线程的并行度(最后有几个锁的对比测试

总结下就是:对相同KEY操作的线程互斥,对不同KEY操作的线程可以并行


KeyLock有如下几个特性

    1、细粒度,高并行性
    2、可重入
    3、公平锁
    4、加锁开销比ReentrantLock大,适用于处理耗时长、key范围大的场景


KeyLock代码如下(注释很少,因为我也不知道该怎么写清楚,能看懂就看,懒得看的直接用就行):

[java]  view plain copy
  1. public class KeyLock<K> {  
  2.     // 保存所有锁定的KEY及其信号量  
  3.     private final ConcurrentMap<K, Semaphore> map = new ConcurrentHashMap<K, Semaphore>();  
  4.     // 保存每个线程锁定的KEY及其锁定计数  
  5.     private final ThreadLocal<Map<K, LockInfo>> local = new ThreadLocal<Map<K, LockInfo>>() {  
  6.         @Override  
  7.         protected Map<K, LockInfo> initialValue() {  
  8.             return new HashMap<K, LockInfo>();  
  9.         }  
  10.     };  
  11.   
  12.     /** 
  13.      * 锁定key,其他等待此key的线程将进入等待,直到调用{@link #unlock(K)} 
  14.      * 使用hashcode和equals来判断key是否相同,因此key必须实现{@link #hashCode()}和 
  15.      * {@link #equals(Object)}方法 
  16.      *  
  17.      * @param key 
  18.      */  
  19.     public void lock(K key) {  
  20.         if (key == null)  
  21.             return;  
  22.         LockInfo info = local.get().get(key);  
  23.         if (info == null) {  
  24.             Semaphore current = new Semaphore(1);  
  25.             current.acquireUninterruptibly();  
  26.             Semaphore previous = map.put(key, current);  
  27.             if (previous != null)  
  28.                 previous.acquireUninterruptibly();  
  29.             local.get().put(key, new LockInfo(current));  
  30.         } else {  
  31.             info.lockCount++;  
  32.         }  
  33.     }  
  34.       
  35.     /** 
  36.      * 释放key,唤醒其他等待此key的线程 
  37.      * @param key 
  38.      */  
  39.     public void unlock(K key) {  
  40.         if (key == null)  
  41.             return;  
  42.         LockInfo info = local.get().get(key);  
  43.         if (info != null && --info.lockCount == 0) {  
  44.             info.current.release();  
  45.             map.remove(key, info.current);  
  46.             local.get().remove(key);  
  47.         }  
  48.     }  
  49.   
  50.     /** 
  51.      * 锁定多个key 
  52.      * 建议在调用此方法前先对keys进行排序,使用相同的锁定顺序,防止死锁发生 
  53.      * @param keys 
  54.      */  
  55.     public void lock(K[] keys) {  
  56.         if (keys == null)  
  57.             return;  
  58.         for (K key : keys) {  
  59.             lock(key);  
  60.         }  
  61.     }  
  62.   
  63.     /** 
  64.      * 释放多个key 
  65.      * @param keys 
  66.      */  
  67.     public void unlock(K[] keys) {  
  68.         if (keys == null)  
  69.             return;  
  70.         for (K key : keys) {  
  71.             unlock(key);  
  72.         }  
  73.     }  
  74.   
  75.     private static class LockInfo {  
  76.         private final Semaphore current;  
  77.         private int lockCount;  
  78.   
  79.         private LockInfo(Semaphore current) {  
  80.             this.current = current;  
  81.             this.lockCount = 1;  
  82.         }  
  83.     }  
  84. }  

KeyLock使用示例

[java]  view plain copy
  1. private int[] accounts;  
  2. private KeyLock<Integer> lock = new KeyLock<Integer>();  
  3.   
  4. public boolean transfer(int from, int to, int money) {  
  5.     Integer[] keys = new Integer[] {from, to};  
  6.     Arrays.sort(keys); //对多个key进行排序,保证锁定顺序防止死锁  
  7.     lock.lock(keys);  
  8.     try {  
  9.         //处理不同的from和to的线程都可进入此同步块  
  10.         if (accounts[from] < money)  
  11.             return false;  
  12.         accounts[from] -= money;  
  13.         accounts[to] += money;  
  14.         return true;  
  15.     } finally {  
  16.         lock.unlock(keys);  
  17.     }  
  18. }  


好,工具有了,接下来就是测试了,为了测出并行度,我把转账过程延长了,加了个sleep(2),使每个转账过程至少要花2毫秒(这只是个demo,真实环境下对数据库操作也很费时)。

测试代码如下:

[java]  view plain copy
  1. //场景:多线程并发转账  
  2. public class Test {  
  3.     private final int[] account; // 账户数组,其索引为账户ID,内容为金额  
  4.   
  5.     public Test(int count, int money) {  
  6.         account = new int[count];  
  7.         Arrays.fill(account, money);  
  8.     }  
  9.   
  10.     boolean transfer(int from, int to, int money) {  
  11.         if (account[from] < money)  
  12.             return false;  
  13.         account[from] -= money;  
  14.         try {  
  15.             Thread.sleep(2);  
  16.         } catch (Exception e) {  
  17.         }  
  18.         account[to] += money;  
  19.         return true;  
  20.     }  
  21.       
  22.     int getAmount() {  
  23.         int result = 0;  
  24.         for (int m : account)  
  25.             result += m;  
  26.         return result;  
  27.     }  
  28.   
  29.     public static void main(String[] args) throws Exception {  
  30.         int count = 100;        //账户个数  
  31.         int money = 10000;      //账户初始金额  
  32.         int threadNum = 8;      //转账线程数  
  33.         int number = 10000;     //转账次数  
  34.         int maxMoney = 1000;    //随机转账最大金额  
  35.         Test test = new Test(count, money);  
  36.           
  37.         //不加锁  
  38. //      Runner runner = test.new NonLockRunner(maxMoney, number);  
  39.         //加synchronized锁  
  40. //      Runner runner = test.new SynchronizedRunner(maxMoney, number);  
  41.         //加ReentrantLock锁  
  42. //      Runner runner = test.new ReentrantLockRunner(maxMoney, number);  
  43.         //加KeyLock锁  
  44.         Runner runner = test.new KeyLockRunner(maxMoney, number);  
  45.           
  46.         Thread[] threads = new Thread[threadNum];  
  47.         for (int i = 0; i < threadNum; i++)  
  48.             threads[i] = new Thread(runner, "thread-" + i);  
  49.         long begin = System.currentTimeMillis();  
  50.         for (Thread t : threads)  
  51.             t.start();  
  52.         for (Thread t : threads)  
  53.             t.join();  
  54.         long time = System.currentTimeMillis() - begin;  
  55.         System.out.println("类型:" + runner.getClass().getSimpleName());  
  56.         System.out.printf("耗时:%dms\n", time);  
  57.         System.out.printf("初始总金额:%d\n", count * money);  
  58.         System.out.printf("终止总金额:%d\n", test.getAmount());  
  59.     }  
  60.   
  61.     // 转账任务  
  62.     abstract class Runner implements Runnable {  
  63.         final int maxMoney;  
  64.         final int number;  
  65.         private final Random random = new Random();  
  66.         private final AtomicInteger count = new AtomicInteger();  
  67.   
  68.         Runner(int maxMoney, int number) {  
  69.             this.maxMoney = maxMoney;  
  70.             this.number = number;  
  71.         }  
  72.   
  73.         @Override  
  74.         public void run() {  
  75.             while(count.getAndIncrement() < number) {  
  76.                 int from = random.nextInt(account.length);  
  77.                 int to;  
  78.                 while ((to = random.nextInt(account.length)) == from)  
  79.                     ;  
  80.                 int money = random.nextInt(maxMoney);  
  81.                 doTransfer(from, to, money);  
  82.             }  
  83.         }  
  84.   
  85.         abstract void doTransfer(int from, int to, int money);  
  86.     }  
  87.   
  88.     // 不加锁的转账  
  89.     class NonLockRunner extends Runner {  
  90.         NonLockRunner(int maxMoney, int number) {  
  91.             super(maxMoney, number);  
  92.         }  
  93.   
  94.         @Override  
  95.         void doTransfer(int from, int to, int money) {  
  96.             transfer(from, to, money);  
  97.         }  
  98.     }  
  99.   
  100.     // synchronized的转账  
  101.     class SynchronizedRunner extends Runner {  
  102.         SynchronizedRunner(int maxMoney, int number) {  
  103.             super(maxMoney, number);  
  104.         }  
  105.   
  106.         @Override  
  107.         synchronized void doTransfer(int from, int to, int money) {  
  108.             transfer(from, to, money);  
  109.         }  
  110.     }  
  111.   
  112.     // ReentrantLock的转账  
  113.     class ReentrantLockRunner extends Runner {  
  114.         private final ReentrantLock lock = new ReentrantLock();  
  115.   
  116.         ReentrantLockRunner(int maxMoney, int number) {  
  117.             super(maxMoney, number);  
  118.         }  
  119.   
  120.         @Override  
  121.         void doTransfer(int from, int to, int money) {  
  122.             lock.lock();  
  123.             try {  
  124.                 transfer(from, to, money);  
  125.             } finally {  
  126.                 lock.unlock();  
  127.             }  
  128.         }  
  129.     }  
  130.   
  131.     // KeyLock的转账  
  132.     class KeyLockRunner extends Runner {  
  133.         private final KeyLock<Integer> lock = new KeyLock<Integer>();  
  134.   
  135.         KeyLockRunner(int maxMoney, int number) {  
  136.             super(maxMoney, number);  
  137.         }  
  138.   
  139.         @Override  
  140.         void doTransfer(int from, int to, int money) {  
  141.             Integer[] keys = new Integer[] {from, to};  
  142.             Arrays.sort(keys);  
  143.             lock.lock(keys);  
  144.             try {  
  145.                 transfer(from, to, money);  
  146.             } finally {  
  147.                 lock.unlock(keys);  
  148.             }  
  149.         }  
  150.     }  
  151. }  
最最重要的 测试结果

(8线程对100个账户随机转账总共10000次):

       类型:NonLockRunner(不加锁)
       耗时:2482ms
       初始总金额:1000000
       终止总金额:998906(无法保证原子性)

       类型:SynchronizedRunner(加synchronized锁)
       耗时:20872ms
       初始总金额:1000000
       终止总金额:1000000

       类型:ReentrantLockRunner(加ReentrantLock锁)
       耗时:21588ms
       初始总金额:1000000
       终止总金额:1000000

       类型:KeyLockRunner(加KeyLock锁)
       耗时:2831ms
       初始总金额:1000000
       终止总金额:1000000


查看文章的评论,发现有人对此进行了相应的整理,整理内容参考:

http://blog.youkuaiyun.com/raistlic/article/details/9612571


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值