Java 实现基于Redis的分布式可重入锁

Java 实现基于Redis的分布式可重入锁

之前在 Java实现基于的Redis的分布式锁 这篇文章中,已经实现了加锁的逻辑,但是有个缺点,就是不可重入,任何重入锁的尝试都会导致死锁的发生,想了一下,这个问题可以解决。

 

 

Thinking

 

如何实现可重入?

 

首先锁信息(指redis中lockKey关联的value值) 必须得设计的能负载更多信息,之前non-reentrant时value直接就是一个超时时间,但是要实现可重入单超时时间是不够的,必须要标识锁是被谁持有的,也就是说要标识分布式环境中的线程,还要记录锁被入了多少次。

 

 

如何在分布式线程中标识唯一线程?

 

MAC地址 + jvm进程ID + 线程ID(或者线程地址都行),三者结合即可唯一分布式环境中的线程。

 

 

实现

 

锁的信息采用json存储,格式如下:

 

 

 

 代码框架还是和之前实现的非重入的差不多,重点是lock方法,代码已有非常详细的注释

 

Java代码 
  1. package cc.lixiaohui.lock.redis;  
  2.   
  3. import java.io.IOException;  
  4. import java.net.SocketAddress;  
  5. import java.util.concurrent.TimeUnit;  
  6.   
  7. import org.slf4j.Logger;  
  8. import org.slf4j.LoggerFactory;  
  9.   
  10. import redis.clients.jedis.Jedis;  
  11. import cc.lixiaohui.lock.AbstractLock;  
  12. import cc.lixiaohui.lock.Lock;  
  13. import cc.lixiaohui.lock.time.nio.client.TimeClient;  
  14. import cc.lixiaohui.lock.util.LockInfo;  
  15.   
  16. /** 
  17.  * 基于Redis的SETNX操作实现的分布式锁, 获取锁时最好用tryLock(long time, TimeUnit unit), 以免网路问题而导致线程一直阻塞. 
  18.  * <a href="http://redis.io/commands/setnx">SETNC操作参考资料.</a> 
  19.  *  
  20.  * <p><b>可重入实现关键:</b> 
  21.  * <ul> 
  22.  * <li>在分布式环境中如何确定一个线程? <i><b>mac地址 + jvm pid + threadId</b></i> (mac地址唯一, jvm 
  23.  * pid在单机内唯一, threadId在单jvm内唯一)</li> 
  24.  * <li>任何一个线程从redis拿到value值后都需要能确定 该锁是否被自己持有, 因此value值要有以下特性: 保存持有锁的主机(mac), jvm 
  25.  * pid, 持有锁的线程ID, 重复持有锁的次数</li> 
  26.  * </ul></p> 
  27.  * <p> 
  28.  * redis中value设计如下(in json): 
  29.  * <pre> 
  30.  * { 
  31.  *  expires : expire time in long 
  32.  *  mac : mac address of lock holder's machine 
  33.  *  pid : jvm process id 
  34.  *  threadId : lock holder thread id 
  35.  *  count : hold count(for use of reentrancy) 
  36.  * } 
  37.  * 由{@link LockInfo LockInfo}表示. 
  38.  * </pre> 
  39.  *  
  40.  * <b>Usage Example:</b> 
  41.  * <pre> 
  42.  *  {@link Lock} lock = new {@link ReentrantLock}(jedis, "lockKey", lockExpires, timeServerAddr); 
  43.  *  if (lock.tryLock(3, TimeUnit.SECONDS)) { 
  44.  *      try { 
  45.  *          // do something 
  46.  *      } catch (Exception e) { 
  47.  *          lock.unlock(); 
  48.  *      } 
  49.  *  } 
  50.  * </pre> 
  51.  * </p> 
  52.  *  
  53.  * @author lixiaohui 
  54.  * @date 2016年9月15日 下午2:52:38 
  55.  * 
  56.  */  
  57. public class ReentrantLock extends AbstractLock {  
  58.   
  59.     private Jedis jedis;  
  60.   
  61.     private TimeClient timeClient;  
  62.   
  63.     // 锁的名字  
  64.     protected String lockKey;  
  65.   
  66.     // 锁的有效时长(毫秒)  
  67.     protected long lockExpires;  
  68.   
  69.     private static final Logger logger = LoggerFactory.getLogger(ReentrantLock.class);  
  70.   
  71.     public ReentrantLock(Jedis jedis, String lockKey, long lockExpires, SocketAddress timeServerAddr) throws IOException {  
  72.         this.jedis = jedis;  
  73.         this.lockKey = lockKey;  
  74.         this.lockExpires = lockExpires;  
  75.         timeClient = new TimeClient(timeServerAddr);  
  76.     }  
  77.   
  78.     // 阻塞式获取锁的实现  
  79.     protected boolean lock(boolean useTimeout, long time, TimeUnit unit, boolean interrupt) throws InterruptedException {  
  80.         if (interrupt) {  
  81.             checkInterruption();  
  82.         }  
  83.   
  84.         // 超时控制 的时间可以从本地获取, 因为这个和锁超时没有关系, 只是一段时间区间的控制  
  85.         long start = localTimeMillis();  
  86.         long timeout = unit.toMillis(time); // if !useTimeout, then it's useless  
  87.   
  88.         // walkthrough  
  89.         // 1. lockKey未关联value, 直接设置lockKey, 成功获取到锁, return true  
  90.         // 2. lock 已过期, 用getset设置lockKey, 判断返回的旧的LockInfo  
  91.         // 2.1 若仍是超时的, 则成功获取到锁, return true  
  92.         // 2.2 若不是超时的, 则进入下一次循环重新开始 步骤1  
  93.         // 3. lock没过期, 判断是否是当前线程持有  
  94.         // 3.1 是, 则计数加 1, return true  
  95.         // 3.2 否, 则进入下一次循环重新开始 步骤1  
  96.         // note: 每次进入循环都检查 : 1.是否超时, 若是则return false; 2.是否检查中断(interrupt)被中断,  
  97.         // 若需检查中断且被中断, 则抛InterruptedException  
  98.         while (useTimeout ? !isTimeout(start, timeout) : true) {  
  99.             if (interrupt) {  
  100.                 checkInterruption();  
  101.             }  
  102.   
  103.             long lockExpireTime = serverTimeMillis() + lockExpires + 1;// 锁超时时间  
  104.             String newLockInfoJson = LockInfo.newForCurrThread(lockExpireTime).toString();  
  105.             if (jedis.setnx(lockKey, newLockInfoJson) == 1) { // 条件能成立的唯一情况就是redis中lockKey还未关联value  
  106.                 // TODO 成功获取到锁, 设置相关标识  
  107.                 logger.debug("{} get lock(new), lockInfo: {}", Thread.currentThread().getName(), newLockInfoJson);  
  108.                 locked = true;  
  109.                 return true;  
  110.             }  
  111.   
  112.             // value已有值, 但不能说明锁被持有, 因为锁可能expired了  
  113.             String currLockInfoJson = jedis.get(lockKey);  
  114.             // 若这瞬间锁被delete了  
  115.             if (currLockInfoJson == null) {  
  116.                 continue;  
  117.             }  
  118.   
  119.             LockInfo currLockInfo = LockInfo.fromString(currLockInfoJson);  
  120.             // 竞争条件只可能出现在锁超时的情况, 因为如果没有超时, 线程发现锁并不是被自己持有, 线程就不会去动value  
  121.             if (isTimeExpired(currLockInfo.getExpires())) {  
  122.                 // 锁超时了  
  123.                 LockInfo oldLockInfo = LockInfo.fromString(jedis.getSet(lockKey, newLockInfoJson));  
  124.                 if (oldLockInfo != null && isTimeExpired(oldLockInfo.getExpires())) {  
  125.                     // TODO 成功获取到锁, 设置相关标识  
  126.                     logger.debug("{} get lock(new), lockInfo: {}", Thread.currentThread().getName(), newLockInfoJson);  
  127.                     locked = true;  
  128.                     return true;  
  129.                 }  
  130.             } else {  
  131.                 // 锁未超时, 不会有竞争情况  
  132.                 if (isHeldByCurrentThread(currLockInfo)) { // 当前线程持有  
  133.                     // TODO 成功获取到锁, 设置相关标识  
  134.                     currLockInfo.setExpires(serverTimeMillis() + lockExpires + 1); // 设置新的锁超时时间  
  135.                     currLockInfo.incCount();  
  136.                     jedis.set(lockKey, currLockInfo.toString());  
  137.                     logger.debug("{} get lock(inc), lockInfo: {}", Thread.currentThread().getName(), currLockInfo);  
  138.                     locked = true;  
  139.                     return true;  
  140.                 }  
  141.             }  
  142.         }  
  143.         locked = false;  
  144.         return false;  
  145.     }  
  146.   
  147.     public boolean tryLock() {  
  148.         long lockExpireTime = serverTimeMillis() + lockExpires + 1;  
  149.         String newLockInfo = LockInfo.newForCurrThread(lockExpireTime).toString();  
  150.   
  151.         if (jedis.setnx(lockKey, newLockInfo) == 1) {  
  152.             locked = true;  
  153.             return true;  
  154.         }  
  155.   
  156.         String currLockInfoJson = jedis.get(lockKey);  
  157.         if (currLockInfoJson == null) {  
  158.             // 再一次尝试获取  
  159.             if (jedis.setnx(lockKey, newLockInfo) == 1) {  
  160.                 locked = true;  
  161.                 return true;  
  162.             } else {  
  163.                 locked = false;  
  164.                 return false;  
  165.             }  
  166.         }  
  167.           
  168.         LockInfo currLockInfo = LockInfo.fromString(currLockInfoJson);  
  169.           
  170.         if (isTimeExpired(currLockInfo.getExpires())) {  
  171.             LockInfo oldLockInfo = LockInfo.fromString(jedis.getSet(lockKey, newLockInfo));  
  172.             if (oldLockInfo != null && isTimeExpired(oldLockInfo.getExpires())) {  
  173.                 locked = true;  
  174.                 return true;  
  175.             }  
  176.         } else {  
  177.             if (isHeldByCurrentThread(currLockInfo)) {  
  178.                 currLockInfo.setExpires(serverTimeMillis() + lockExpires + 1);   
  179.                 currLockInfo.incCount();  
  180.                 jedis.set(lockKey, currLockInfo.toString());  
  181.                 locked = true;  
  182.                 return true;  
  183.             }  
  184.         }  
  185.         locked = false;  
  186.         return false;  
  187.     }  
  188.   
  189.     /** 
  190.      * Queries if this lock is held by any thread. 
  191.      *  
  192.      * @return {@code true} if any thread holds this lock and {@code false} 
  193.      *         otherwise 
  194.      */  
  195.     public boolean isLocked() {  
  196.         // walkthrough  
  197.         // 1. lockKey未关联value, return false  
  198.         // 2. 若 lock 已过期, return false, 否则 return true  
  199.         if (!locked) { // 本地locked为false, 肯定没加锁  
  200.             return false;  
  201.         }  
  202.         String json = jedis.get(lockKey);  
  203.         if (json == null) {  
  204.             return false;  
  205.         }  
  206.         if (isTimeExpired(LockInfo.fromString(json).getExpires())) {  
  207.             return false;  
  208.         }  
  209.         return true;  
  210.     }  
  211.   
  212.     @Override  
  213.     protected void unlock0() {  
  214.         // walkthrough  
  215.         // 1. 若锁过期, return  
  216.         // 2. 判断自己是否是锁的owner  
  217.         // 2.1 是, 若 count = 1, 则删除lockKey; 若 count > 1, 则计数减 1, return  
  218.         // 2.2 否, 则抛异常 IllegalMonitorStateException, reutrn  
  219.         // done, return  
  220.         LockInfo currLockInfo = LockInfo.fromString(jedis.get(lockKey));  
  221.         if (isTimeExpired(currLockInfo.getExpires())) {  
  222.             return;  
  223.         }  
  224.   
  225.         if (isHeldByCurrentThread(currLockInfo)) {  
  226.             if (currLockInfo.getCount() == 1) {  
  227.                 jedis.del(lockKey);  
  228.                 logger.debug("{} unlock(del), lockInfo: null", Thread.currentThread().getName());  
  229.             } else {  
  230.                 currLockInfo.decCount(); // 持有锁计数减1  
  231.                 String json = currLockInfo.toString();  
  232.                 jedis.set(lockKey, json);  
  233.                 logger.debug("{} unlock(dec), lockInfo: {}", Thread.currentThread().getName(), json);  
  234.             }  
  235.         } else {  
  236.             throw new IllegalMonitorStateException(String.format("current thread[%s] does not holds the lock", Thread.currentThread().toString()));  
  237.         }  
  238.   
  239.     }  
  240.   
  241.     public void release() {  
  242.         jedis.close();  
  243.         timeClient.close();  
  244.     }  
  245.       
  246.     public boolean isHeldByCurrentThread() {  
  247.         return isHeldByCurrentThread(LockInfo.fromString(jedis.get(lockKey)));  
  248.     }  
  249.   
  250.     // ------------------- utility methods ------------------------  
  251.   
  252.     private boolean isHeldByCurrentThread(LockInfo lockInfo) {  
  253.         return lockInfo.isCurrentThread();  
  254.     }  
  255.   
  256.     private void checkInterruption() throws InterruptedException {  
  257.         if (Thread.currentThread().isInterrupted()) {  
  258.             throw new InterruptedException();  
  259.         }  
  260.     }  
  261.   
  262.     private boolean isTimeExpired(long time) {  
  263.         return time < serverTimeMillis();  
  264.     }  
  265.   
  266.     private boolean isTimeout(long start, long timeout) {  
  267.         // 这里拿本地的时间来比较  
  268.         return start + timeout < System.currentTimeMillis();  
  269.     }  
  270.   
  271.     private long serverTimeMillis() {  
  272.         return timeClient.currentTimeMillis();  
  273.     }  
  274.   
  275.     private long localTimeMillis() {  
  276.         return System.currentTimeMillis();  
  277.     }  
  278.   
  279. }  

 

 测试

 

5个线程,每个线程都是不同的jedis连接,模拟分布式环境,线程的任务就是不断的去尝试重入地获取锁,重入的次数为随机但在0-5之间。

 

代码

 

Java代码 
  1. package cc.lixiaohui.DistributedLock.DistributedLock;  
  2.   
  3. import java.io.IOException;  
  4. import java.net.InetSocketAddress;  
  5. import java.net.SocketAddress;  
  6. import java.util.ArrayList;  
  7. import java.util.List;  
  8. import java.util.Random;  
  9. import java.util.concurrent.TimeUnit;  
  10.   
  11. import org.junit.Test;  
  12.   
  13. import redis.clients.jedis.Jedis;  
  14. import cc.lixiaohui.lock.redis.ReentrantLock;  
  15.   
  16. /** 
  17.  * @author lixiaohui 
  18.  * @date 2016年9月28日 下午8:41:36 
  19.  *  
  20.  */  
  21. public class ReentrantTest {  
  22.       
  23.     final int EXPIRES = 10 * 1000;  
  24.       
  25.     final String LOCK_KEY = "lock.lock";  
  26.       
  27.     final SocketAddress TIME_SERVER_ADDR = new InetSocketAddress("localhost"9999);  
  28.       
  29.     @Test  
  30.     public void test() throws Exception {  
  31.         // 创建5个线程不停地去重入(随机次数n, 0 <= n <=5)获取锁  
  32.         List<Thread> threads = createThreads(5);  
  33.         //开始任务  
  34.         for (Thread t : threads) {  
  35.             t.start();  
  36.         }  
  37.         // 执行60秒  
  38.         Thread.sleep(60 * 1000);  
  39.         //停止所有线程  
  40.         Task.alive = false;  
  41.         // 等待所有线程终止  
  42.         for (Thread t : threads) {  
  43.             t.join();  
  44.         }  
  45.           
  46.     }  
  47.     // 创建count个线程,每个线程都是不同的jedis连接以及不同的与时间服务器的连接  
  48.     private List<Thread> createThreads(int count) throws IOException {  
  49.         List<Thread> threads = new ArrayList<Thread>();  
  50.         for (int i = 0; i < count; i++) {  
  51.             Jedis jedis = new Jedis("localhost"6379);  
  52.             ReentrantLock lock = new ReentrantLock(jedis, LOCK_KEY, EXPIRES, TIME_SERVER_ADDR);  
  53.             Task task = new Task(lock);  
  54.             Thread t = new Thread(task);  
  55.             threads.add(t);  
  56.         }  
  57.         return threads;  
  58.     }  
  59.       
  60.     private static class Task implements Runnable {  
  61.           
  62.         private ReentrantLock lock;  
  63.           
  64.         private final int MAX_ENTRANT = 5;  
  65.           
  66.         private final Random random = new Random();  
  67.           
  68.         private static boolean alive = true;  
  69.           
  70.         Task(ReentrantLock lock) {  
  71.             this.lock = lock;  
  72.         }  
  73.           
  74.         public void run() {  
  75.             while (alive) {  
  76.                 int times = random.nextInt(MAX_ENTRANT);  
  77.                 doLock(times);  
  78.             }  
  79.         }  
  80.           
  81.         private void doLock(int times) {  
  82.             if (lock.tryLock(5, TimeUnit.SECONDS)) {  
  83.                 try {  
  84.                     if (times > 0) {  
  85.                         doLock(--times);  
  86.                     }  
  87.                 } finally {  
  88.                     if (lock != null) {  
  89.                         lock.unlock();  
  90.                     }  
  91.                 }  
  92.             }  
  93.               
  94.         }  
  95.           
  96.           
  97.           
  98.     }  
  99.       
  100. }  

 

测试结果

 

下面是一部分日志输出:

Java代码 
  1. 21:09:22.328-[DEBUG] Thread-0 ReentrantLock - Thread-0 get lock(new), lockInfo: {"count":1,"expires":1475068172329,"jvmPid":22224,"mac":"28-D2-44-0E-0D-9A","threadId":11}  
  2. 21:09:22.330-[DEBUG] Thread-0 ReentrantLock - Thread-0 get lock(inc), lockInfo: {"count":2,"expires":1475068172330,"jvmPid":22224,"mac":"28-D2-44-0E-0D-9A","threadId":11}  
  3. 21:09:22.331-[DEBUG] Thread-0 ReentrantLock - Thread-0 get lock(inc), lockInfo: {"count":3,"expires":1475068172332,"jvmPid":22224,"mac":"28-D2-44-0E-0D-9A","threadId":11}  
  4. 21:09:22.332-[DEBUG] Thread-0 ReentrantLock - Thread-0 get lock(inc), lockInfo: {"count":4,"expires":1475068172333,"jvmPid":22224,"mac":"28-D2-44-0E-0D-9A","threadId":11}  
  5. 21:09:22.334-[DEBUG] Thread-0 ReentrantLock - Thread-0 get lock(inc), lockInfo: {"count":5,"expires":1475068172334,"jvmPid":22224,"mac":"28-D2-44-0E-0D-9A","threadId":11}  
  6. 21:09:22.335-[DEBUG] Thread-0 ReentrantLock - Thread-0 unlock(dec), lockInfo: {"count":4,"expires":1475068172334,"jvmPid":22224,"mac":"28-D2-44-0E-0D-9A","threadId":11}  
  7. 21:09:22.336-[DEBUG] Thread-0 ReentrantLock - Thread-0 unlock(dec), lockInfo: {"count":3,"expires":1475068172334,"jvmPid":22224,"mac":"28-D2-44-0E-0D-9A","threadId":11}  
  8. 21:09:22.338-[DEBUG] Thread-0 ReentrantLock - Thread-0 unlock(dec), lockInfo: {"count":2,"expires":1475068172334,"jvmPid":22224,"mac":"28-D2-44-0E-0D-9A","threadId":11}  
  9. 21:09:22.339-[DEBUG] Thread-0 ReentrantLock - Thread-0 unlock(dec), lockInfo: {"count":1,"expires":1475068172334,"jvmPid":22224,"mac":"28-D2-44-0E-0D-9A","threadId":11}  
  10. 21:09:22.340-[DEBUG] Thread-0 ReentrantLock - Thread-0 unlock(del), lockInfo: null  
  11. 21:09:22.341-[DEBUG] Thread-0 ReentrantLock - Thread-0 get lock(new), lockInfo: {"count":1,"expires":1475068172341,"jvmPid":22224,"mac":"28-D2-44-0E-0D-9A","threadId":11}  
  12. 21:09:22.341-[DEBUG] Thread-0 ReentrantLock - Thread-0 unlock(del), lockInfo: null  
  13. 21:09:22.342-[DEBUG] Thread-0 ReentrantLock - Thread-0 get lock(new), lockInfo: {"count":1,"expires":1475068172342,"jvmPid":22224,"mac":"28-D2-44-0E-0D-9A","threadId":11}  
  14. 21:09:22.343-[DEBUG] Thread-0 ReentrantLock - Thread-0 get lock(inc), lockInfo: {"count":2,"expires":1475068172344,"jvmPid":22224,"mac":"28-D2-44-0E-0D-9A","threadId":11}  
  15. 21:09:22.344-[DEBUG] Thread-0 ReentrantLock - Thread-0 unlock(dec), lockInfo: {"count":1,"expires":1475068172344,"jvmPid":22224,"mac":"28-D2-44-0E-0D-9A","threadId":11}  
  16. 21:09:22.345-[DEBUG] Thread-0 ReentrantLock - Thread-0 unlock(del), lockInfo: null  
  17. 21:09:22.345-[DEBUG] Thread-3 ReentrantLock - Thread-3 get lock(new), lockInfo: {"count":1,"expires":1475068172345,"jvmPid":22224,"mac":"28-D2-44-0E-0D-9A","threadId":14}  
  18. 21:09:22.346-[DEBUG] Thread-3 ReentrantLock - Thread-3 get lock(inc), lockInfo: {"count":2,"expires":1475068172347,"jvmPid":22224,"mac":"28-D2-44-0E-0D-9A","threadId":14}  
  19. 21:09:22.347-[DEBUG] Thread-3 ReentrantLock - Thread-3 get lock(inc), lockInfo: {"count":3,"expires":1475068172348,"jvmPid":22224,"mac":"28-D2-44-0E-0D-9A","threadId":14}  
  20. 21:09:22.349-[DEBUG] Thread-3 ReentrantLock - Thread-3 get lock(inc), lockInfo: {"count":4,"expires":1475068172350,"jvmPid":22224,"mac":"28-D2-44-0E-0D-9A","threadId":14}  
  21. 21:09:22.350-[DEBUG] Thread-3 ReentrantLock - Thread-3 unlock(dec), lockInfo: {"count":3,"expires":1475068172350,"jvmPid":22224,"mac":"28-D2-44-0E-0D-9A","threadId":14}  
  22. 21:09:22.350-[DEBUG] Thread-3 ReentrantLock - Thread-3 unlock(dec), lockInfo: {"count":2,"expires":1475068172350,"jvmPid":22224,"mac":"28-D2-44-0E-0D-9A","threadId":14}  
  23. 21:09:22.351-[DEBUG] Thread-3 ReentrantLock - Thread-3 unlock(dec), lockInfo: {"count":1,"expires":1475068172350,"jvmPid":22224,"mac":"28-D2-44-0E-0D-9A","threadId":14}  
  24. 21:09:22.351-[DEBUG] Thread-3 ReentrantLock - Thread-3 unlock(del), lockInfo: null  
  25. 21:09:22.352-[DEBUG] Thread-3 ReentrantLock - Thread-3 get lock(new), lockInfo: {"count":1,"expires":1475068172352,"jvmPid":22224,"mac":"28-D2-44-0E-0D-9A","threadId":14}  
  26. 21:09:22.352-[DEBUG] Thread-3 ReentrantLock - Thread-3 unlock(del), lockInfo: null  
  27. 21:09:22.352-[DEBUG] Thread-0 ReentrantLock - Thread-0 get lock(new), lockInfo: {"count":1,"expires":1475068172353,"jvmPid":22224,"mac":"28-D2-44-0E-0D-9A","threadId":11}  
  28. 21:09:22.354-[DEBUG] Thread-0 ReentrantLock - Thread-0 get lock(inc), lockInfo: {"count":2,"expires":1475068172355,"jvmPid":22224,"mac":"28-D2-44-0E-0D-9A","threadId":11}  
  29. 21:09:22.354-[DEBUG] Thread-0 ReentrantLock - Thread-0 unlock(dec), lockInfo: {"count":1,"expires":1475068172355,"jvmPid":22224,"mac":"28-D2-44-0E-0D-9A","threadId":11}  
  30. 21:09:22.355-[DEBUG] Thread-0 ReentrantLock - Thread-0 unlock(del), lockInfo: null  
  31. 21:09:22.355-[DEBUG] Thread-4 ReentrantLock - Thread-4 get lock(new), lockInfo: {"count":1,"expires":1475068172356,"jvmPid":22224,"mac":"28-D2-44-0E-0D-9A","threadId":15}  
  32. 21:09:22.357-[DEBUG] Thread-4 ReentrantLock - Thread-4 get lock(inc), lockInfo: {"count":2,"expires":1475068172357,"jvmPid":22224,"mac":"28-D2-44-0E-0D-9A","threadId":15}  
  33. 21:09:22.358-[DEBUG] Thread-4 ReentrantLock - Thread-4 get lock(inc), lockInfo: {"count":3,"expires":1475068172358,"jvmPid":22224,"mac":"28-D2-44-0E-0D-9A","threadId":15}  
  34. 21:09:22.359-[DEBUG] Thread-4 ReentrantLock - Thread-4 get lock(inc), lockInfo: {"count":4,"expires":1475068172360,"jvmPid":22224,"mac":"28-D2-44-0E-0D-9A","threadId":15}  
  35. 21:09:22.360-[DEBUG] Thread-4 ReentrantLock - Thread-4 unlock(dec), lockInfo: {"count":3,"expires":1475068172360,"jvmPid":22224,"mac":"28-D2-44-0E-0D-9A","threadId":15}  
  36. 21:09:22.361-[DEBUG] Thread-4 ReentrantLock - Thread-4 unlock(dec), lockInfo: {"count":2,"expires":1475068172360,"jvmPid":22224,"mac":"28-D2-44-0E-0D-9A","threadId":15}  
  37. 21:09:22.361-[DEBUG] Thread-4 ReentrantLock - Thread-4 unlock(dec), lockInfo: {"count":1,"expires":1475068172360,"jvmPid":22224,"mac":"28-D2-44-0E-0D-9A","threadId":15}  
  38. 21:09:22.362-[DEBUG] Thread-4 ReentrantLock - Thread-4 unlock(del), lockInfo: null  
  39. 21:09:22.362-[DEBUG] Thread-0 ReentrantLock - Thread-0 get lock(new), lockInfo: {"count":1,"expires":1475068172363,"jvmPid":22224,"mac":"28-D2-44-0E-0D-9A","threadId":11}  
  40. 21:09:22.363-[DEBUG] Thread-0 ReentrantLock - Thread-0 get lock(inc), lockInfo: {"count":2,"expires":1475068172364,"jvmPid":22224,"mac":"28-D2-44-0E-0D-9A","threadId":11}  
  41. 21:09:22.365-[DEBUG] Thread-0 ReentrantLock - Thread-0 get lock(inc), lockInfo: {"count":3,"expires":1475068172365,"jvmPid":22224,"mac":"28-D2-44-0E-0D-9A","threadId":11}  
  42. 21:09:22.365-[DEBUG] Thread-0 ReentrantLock - Thread-0 unlock(dec), lockInfo: {"count":2,"expires":1475068172365,"jvmPid":22224,"mac":"28-D2-44-0E-0D-9A","threadId":11}  
  43. 21:09:22.366-[DEBUG] Thread-0 ReentrantLock - Thread-0 unlock(dec), lockInfo: {"count":1,"expires":1475068172365,"jvmPid":22224,"mac":"28-D2-44-0E-0D-9A","threadId":11}  
  44. 21:09:22.367-[DEBUG] Thread-0 ReentrantLock - Thread-0 unlock(del), lockInfo: null  
  45. 21:09:22.367-[DEBUG] Thread-4 ReentrantLock - Thread-4 get lock(new), lockInfo: {"count":1,"expires":1475068172368,"jvmPid":22224,"mac":"28-D2-44-0E-0D-9A","threadId":15}  
  46. 21:09:22.368-[DEBUG] Thread-4 ReentrantLock - Thread-4 get lock(inc), lockInfo: {"count":2,"expires":1475068172369,"jvmPid":22224,"mac":"28-D2-44-0E-0D-9A","threadId":15}  
  47. 21:09:22.370-[DEBUG] Thread-4 ReentrantLock - Thread-4 unlock(dec), lockInfo: {"count":1,"expires":1475068172369,"jvmPid":22224,"mac":"28-D2-44-0E-0D-9A","threadId":15}  
  48. 21:09:22.372-[DEBUG] Thread-4 ReentrantLock - Thread-4 unlock(del), lockInfo: null  
  49. 21:09:22.372-[DEBUG] Thread-1 ReentrantLock - Thread-1 get lock(new), lockInfo: {"count":1,"expires":1475068172373,"jvmPid":22224,"mac":"28-D2-44-0E-0D-9A","threadId":12}  
  50. 21:09:22.374-[DEBUG] Thread-1 ReentrantLock - Thread-1 get lock(inc), lockInfo: {"count":2,"expires":1475068172374,"jvmPid":22224,"mac":"28-D2-44-0E-0D-9A","threadId":12}  
  51. 21:09:22.375-[DEBUG] Thread-1 ReentrantLock - Thread-1 get lock(inc), lockInfo: {"count":3,"expires":1475068172376,"jvmPid":22224,"mac":"28-D2-44-0E-0D-9A","threadId":12}  
  52. 21:09:22.376-[DEBUG] Thread-1 ReentrantLock - Thread-1 get lock(inc), lockInfo: {"count":4,"expires":1475068172376,"jvmPid":22224,"mac":"28-D2-44-0E-0D-9A","threadId":12}  
  53. 21:09:22.376-[DEBUG] Thread-1 ReentrantLock - Thread-1 get lock(inc), lockInfo: {"count":5,"expires":1475068172377,"jvmPid":22224,"mac":"28-D2-44-0E-0D-9A","threadId":12}  
  54. 21:09:22.377-[DEBUG] Thread-1 ReentrantLock - Thread-1 unlock(dec), lockInfo: {"count":4,"expires":1475068172377,"jvmPid":22224,"mac":"28-D2-44-0E-0D-9A","threadId":12}  
  55. 21:09:22.377-[DEBUG] Thread-1 ReentrantLock - Thread-1 unlock(dec), lockInfo: {"count":3,"expires":1475068172377,"jvmPid":22224,"mac":"28-D2-44-0E-0D-9A","threadId":12}  
  56. 21:09:22.378-[DEBUG] Thread-1 ReentrantLock - Thread-1 unlock(dec), lockInfo: {"count":2,"expires":1475068172377,"jvmPid":22224,"mac":"28-D2-44-0E-0D-9A","threadId":12}  
  57. 21:09:22.378-[DEBUG] Thread-1 ReentrantLock - Thread-1 unlock(dec), lockInfo: {"count":1,"expires":1475068172377,"jvmPid":22224,"mac":"28-D2-44-0E-0D-9A","threadId":12}  
  58. 21:09:22.379-[DEBUG] Thread-1 ReentrantLock - Thread-1 unlock(del), lockInfo: null  
  59. 21:09:22.379-[DEBUG] Thread-2 ReentrantLock - Thread-2 get lock(new), lockInfo: {"count":1,"expires":1475068172380,"jvmPid":22224,"mac":"28-D2-44-0E-0D-9A","threadId":13}  
  60. 21:09:22.380-[DEBUG] Thread-2 ReentrantLock - Thread-2 get lock(inc), lockInfo: {"count":2,"expires":1475068172380,"jvmPid":22224,"mac":"28-D2-44-0E-0D-9A","threadId":13}  
  61. 21:09:22.380-[DEBUG] Thread-2 ReentrantLock - Thread-2 unlock(dec), lockInfo: {"count":1,"expires":1475068172380,"jvmPid":22224,"mac":"28-D2-44-0E-0D-9A","threadId":13}  
  62. 21:09:22.380-[DEBUG] Thread-2 ReentrantLock - Thread-2 unlock(del), lockInfo: null  
  63. 21:09:22.380-[DEBUG] Thread-3 ReentrantLock - Thread-3 get lock(new), lockInfo: {"count":1,"expires":1475068172381,"jvmPid":22224,"mac":"28-D2-44-0E-0D-9A","threadId":14}  
  64. 21:09:22.381-[DEBUG] Thread-3 ReentrantLock - Thread-3 get lock(inc), lockInfo: {"count":2,"expires":1475068172382,"jvmPid":22224,"mac":"28-D2-44-0E-0D-9A","threadId":14}  
  65. 21:09:22.381-[DEBUG] Thread-3 ReentrantLock - Thread-3 get lock(inc), lockInfo: {"count":3,"expires":1475068172382,"jvmPid":22224,"mac":"28-D2-44-0E-0D-9A","threadId":14}  
  66. 21:09:22.382-[DEBUG] Thread-3 ReentrantLock - Thread-3 unlock(dec), lockInfo: {"count":2,"expires":1475068172382,"jvmPid":22224,"mac":"28-D2-44-0E-0D-9A","threadId":14}  
  67. 21:09:22.382-[DEBUG] Thread-3 ReentrantLock - Thread-3 unlock(dec), lockInfo: {"count":1,"expires":1475068172382,"jvmPid":22224,"mac":"28-D2-44-0E-0D-9A","threadId":14}  
  68. 21:09:22.382-[DEBUG] Thread-3 ReentrantLock - Thread-3 unlock(del), lockInfo: null  

 看日志输出,lockInfo对应的json就是redis中lockKey对应的值,可以看到这个重入锁正常工作(count先递增后递减,在count不为0时别的线程拿不到锁)。测试通过,性能上还待改善

 

 

Thinking again

 

如何实现读写锁?

 

目前想出的一种实现是redis中存两个键值对,一个读一个写,随之而来的一个问题是:对于加锁过程,可能会要求对这两个键值的更改(这里指一起更改两者)要具有原子性,因此得用一个额外的重入锁,来同步这个操作。但这样实现未免代价太大,仍思考解决方法中..........路过的大神请指条明路...

 

 代码放这里了:戳我

你可能感兴趣的:(java,redis,ReentrantLock,分布式锁,可重入锁)