Java 实现基于Redis的分布式可重入锁
之前在 Java实现基于的Redis的分布式锁 这篇文章中,已经实现了加锁的逻辑,但是有个缺点,就是不可重入,任何重入锁的尝试都会导致死锁的发生,想了一下,这个问题可以解决。
Thinking
如何实现可重入?
首先锁信息(指redis中lockKey关联的value值) 必须得设计的能负载更多信息,之前non-reentrant时value直接就是一个超时时间,但是要实现可重入单超时时间是不够的,必须要标识锁是被谁持有的,也就是说要标识分布式环境中的线程,还要记录锁被入了多少次。
如何在分布式线程中标识唯一线程?
MAC地址 + jvm进程ID + 线程ID(或者线程地址都行),三者结合即可唯一分布式环境中的线程。
实现
锁的信息采用json存储,格式如下:
代码框架还是和之前实现的非重入的差不多,重点是lock方法,代码已有非常详细的注释
- package cc.lixiaohui.lock.redis;
- import java.io.IOException;
- import java.net.SocketAddress;
- import java.util.concurrent.TimeUnit;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import redis.clients.jedis.Jedis;
- import cc.lixiaohui.lock.AbstractLock;
- import cc.lixiaohui.lock.Lock;
- import cc.lixiaohui.lock.time.nio.client.TimeClient;
- import cc.lixiaohui.lock.util.LockInfo;
- /**
- * 基于Redis的SETNX操作实现的分布式锁, 获取锁时最好用tryLock(long time, TimeUnit unit), 以免网路问题而导致线程一直阻塞.
- * <a href="http://redis.io/commands/setnx">SETNC操作参考资料.</a>
- *
- * <p><b>可重入实现关键:</b>
- * <ul>
- * <li>在分布式环境中如何确定一个线程? <i><b>mac地址 + jvm pid + threadId</b></i> (mac地址唯一, jvm
- * pid在单机内唯一, threadId在单jvm内唯一)</li>
- * <li>任何一个线程从redis拿到value值后都需要能确定 该锁是否被自己持有, 因此value值要有以下特性: 保存持有锁的主机(mac), jvm
- * pid, 持有锁的线程ID, 重复持有锁的次数</li>
- * </ul></p>
- * <p>
- * redis中value设计如下(in json):
- * <pre>
- * {
- * expires : expire time in long
- * mac : mac address of lock holder's machine
- * pid : jvm process id
- * threadId : lock holder thread id
- * count : hold count(for use of reentrancy)
- * }
- * 由{@link LockInfo LockInfo}表示.
- * </pre>
- *
- * <b>Usage Example:</b>
- * <pre>
- * {@link Lock} lock = new {@link ReentrantLock}(jedis, "lockKey", lockExpires, timeServerAddr);
- * if (lock.tryLock(3, TimeUnit.SECONDS)) {
- * try {
- * // do something
- * } catch (Exception e) {
- * lock.unlock();
- * }
- * }
- * </pre>
- * </p>
- *
- * @author lixiaohui
- * @date 2016年9月15日 下午2:52:38
- *
- */
- public class ReentrantLock extends AbstractLock {
- private Jedis jedis;
- private TimeClient timeClient;
- // 锁的名字
- protected String lockKey;
- // 锁的有效时长(毫秒)
- protected long lockExpires;
- private static final Logger logger = LoggerFactory.getLogger(ReentrantLock.class);
- public ReentrantLock(Jedis jedis, String lockKey, long lockExpires, SocketAddress timeServerAddr) throws IOException {
- this.jedis = jedis;
- this.lockKey = lockKey;
- this.lockExpires = lockExpires;
- timeClient = new TimeClient(timeServerAddr);
- }
- // 阻塞式获取锁的实现
- protected boolean lock(boolean useTimeout, long time, TimeUnit unit, boolean interrupt) throws InterruptedException {
- if (interrupt) {
- checkInterruption();
- }
- // 超时控制 的时间可以从本地获取, 因为这个和锁超时没有关系, 只是一段时间区间的控制
- long start = localTimeMillis();
- long timeout = unit.toMillis(time); // if !useTimeout, then it's useless
- // walkthrough
- // 1. lockKey未关联value, 直接设置lockKey, 成功获取到锁, return true
- // 2. lock 已过期, 用getset设置lockKey, 判断返回的旧的LockInfo
- // 2.1 若仍是超时的, 则成功获取到锁, return true
- // 2.2 若不是超时的, 则进入下一次循环重新开始 步骤1
- // 3. lock没过期, 判断是否是当前线程持有
- // 3.1 是, 则计数加 1, return true
- // 3.2 否, 则进入下一次循环重新开始 步骤1
- // note: 每次进入循环都检查 : 1.是否超时, 若是则return false; 2.是否检查中断(interrupt)被中断,
- // 若需检查中断且被中断, 则抛InterruptedException
- while (useTimeout ? !isTimeout(start, timeout) : true) {
- if (interrupt) {
- checkInterruption();
- }
- long lockExpireTime = serverTimeMillis() + lockExpires + 1;// 锁超时时间
- String newLockInfoJson = LockInfo.newForCurrThread(lockExpireTime).toString();
- if (jedis.setnx(lockKey, newLockInfoJson) == 1) { // 条件能成立的唯一情况就是redis中lockKey还未关联value
- // TODO 成功获取到锁, 设置相关标识
- logger.debug("{} get lock(new), lockInfo: {}", Thread.currentThread().getName(), newLockInfoJson);
- locked = true;
- return true;
- }
- // value已有值, 但不能说明锁被持有, 因为锁可能expired了
- String currLockInfoJson = jedis.get(lockKey);
- // 若这瞬间锁被delete了
- if (currLockInfoJson == null) {
- continue;
- }
- LockInfo currLockInfo = LockInfo.fromString(currLockInfoJson);
- // 竞争条件只可能出现在锁超时的情况, 因为如果没有超时, 线程发现锁并不是被自己持有, 线程就不会去动value
- if (isTimeExpired(currLockInfo.getExpires())) {
- // 锁超时了
- LockInfo oldLockInfo = LockInfo.fromString(jedis.getSet(lockKey, newLockInfoJson));
- if (oldLockInfo != null && isTimeExpired(oldLockInfo.getExpires())) {
- // TODO 成功获取到锁, 设置相关标识
- logger.debug("{} get lock(new), lockInfo: {}", Thread.currentThread().getName(), newLockInfoJson);
- locked = true;
- return true;
- }
- } else {
- // 锁未超时, 不会有竞争情况
- if (isHeldByCurrentThread(currLockInfo)) { // 当前线程持有
- // TODO 成功获取到锁, 设置相关标识
- currLockInfo.setExpires(serverTimeMillis() + lockExpires + 1); // 设置新的锁超时时间
- currLockInfo.incCount();
- jedis.set(lockKey, currLockInfo.toString());
- logger.debug("{} get lock(inc), lockInfo: {}", Thread.currentThread().getName(), currLockInfo);
- locked = true;
- return true;
- }
- }
- }
- locked = false;
- return false;
- }
- public boolean tryLock() {
- long lockExpireTime = serverTimeMillis() + lockExpires + 1;
- String newLockInfo = LockInfo.newForCurrThread(lockExpireTime).toString();
- if (jedis.setnx(lockKey, newLockInfo) == 1) {
- locked = true;
- return true;
- }
- String currLockInfoJson = jedis.get(lockKey);
- if (currLockInfoJson == null) {
- // 再一次尝试获取
- if (jedis.setnx(lockKey, newLockInfo) == 1) {
- locked = true;
- return true;
- } else {
- locked = false;
- return false;
- }
- }
- LockInfo currLockInfo = LockInfo.fromString(currLockInfoJson);
- if (isTimeExpired(currLockInfo.getExpires())) {
- LockInfo oldLockInfo = LockInfo.fromString(jedis.getSet(lockKey, newLockInfo));
- if (oldLockInfo != null && isTimeExpired(oldLockInfo.getExpires())) {
- locked = true;
- return true;
- }
- } else {
- if (isHeldByCurrentThread(currLockInfo)) {
- currLockInfo.setExpires(serverTimeMillis() + lockExpires + 1);
- currLockInfo.incCount();
- jedis.set(lockKey, currLockInfo.toString());
- locked = true;
- return true;
- }
- }
- locked = false;
- return false;
- }
- /**
- * Queries if this lock is held by any thread.
- *
- * @return {@code true} if any thread holds this lock and {@code false}
- * otherwise
- */
- public boolean isLocked() {
- // walkthrough
- // 1. lockKey未关联value, return false
- // 2. 若 lock 已过期, return false, 否则 return true
- if (!locked) { // 本地locked为false, 肯定没加锁
- return false;
- }
- String json = jedis.get(lockKey);
- if (json == null) {
- return false;
- }
- if (isTimeExpired(LockInfo.fromString(json).getExpires())) {
- return false;
- }
- return true;
- }
- @Override
- protected void unlock0() {
- // walkthrough
- // 1. 若锁过期, return
- // 2. 判断自己是否是锁的owner
- // 2.1 是, 若 count = 1, 则删除lockKey; 若 count > 1, 则计数减 1, return
- // 2.2 否, 则抛异常 IllegalMonitorStateException, reutrn
- // done, return
- LockInfo currLockInfo = LockInfo.fromString(jedis.get(lockKey));
- if (isTimeExpired(currLockInfo.getExpires())) {
- return;
- }
- if (isHeldByCurrentThread(currLockInfo)) {
- if (currLockInfo.getCount() == 1) {
- jedis.del(lockKey);
- logger.debug("{} unlock(del), lockInfo: null", Thread.currentThread().getName());
- } else {
- currLockInfo.decCount(); // 持有锁计数减1
- String json = currLockInfo.toString();
- jedis.set(lockKey, json);
- logger.debug("{} unlock(dec), lockInfo: {}", Thread.currentThread().getName(), json);
- }
- } else {
- throw new IllegalMonitorStateException(String.format("current thread[%s] does not holds the lock", Thread.currentThread().toString()));
- }
- }
- public void release() {
- jedis.close();
- timeClient.close();
- }
- public boolean isHeldByCurrentThread() {
- return isHeldByCurrentThread(LockInfo.fromString(jedis.get(lockKey)));
- }
- // ------------------- utility methods ------------------------
- private boolean isHeldByCurrentThread(LockInfo lockInfo) {
- return lockInfo.isCurrentThread();
- }
- private void checkInterruption() throws InterruptedException {
- if (Thread.currentThread().isInterrupted()) {
- throw new InterruptedException();
- }
- }
- private boolean isTimeExpired(long time) {
- return time < serverTimeMillis();
- }
- private boolean isTimeout(long start, long timeout) {
- // 这里拿本地的时间来比较
- return start + timeout < System.currentTimeMillis();
- }
- private long serverTimeMillis() {
- return timeClient.currentTimeMillis();
- }
- private long localTimeMillis() {
- return System.currentTimeMillis();
- }
- }
测试
5个线程,每个线程都是不同的jedis连接,模拟分布式环境,线程的任务就是不断的去尝试重入地获取锁,重入的次数为随机但在0-5之间。
代码
- package cc.lixiaohui.DistributedLock.DistributedLock;
- import java.io.IOException;
- import java.net.InetSocketAddress;
- import java.net.SocketAddress;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Random;
- import java.util.concurrent.TimeUnit;
- import org.junit.Test;
- import redis.clients.jedis.Jedis;
- import cc.lixiaohui.lock.redis.ReentrantLock;
- /**
- * @author lixiaohui
- * @date 2016年9月28日 下午8:41:36
- *
- */
- public class ReentrantTest {
- final int EXPIRES = 10 * 1000;
- final String LOCK_KEY = "lock.lock";
- final SocketAddress TIME_SERVER_ADDR = new InetSocketAddress("localhost", 9999);
- @Test
- public void test() throws Exception {
- // 创建5个线程不停地去重入(随机次数n, 0 <= n <=5)获取锁
- List<Thread> threads = createThreads(5);
- //开始任务
- for (Thread t : threads) {
- t.start();
- }
- // 执行60秒
- Thread.sleep(60 * 1000);
- //停止所有线程
- Task.alive = false;
- // 等待所有线程终止
- for (Thread t : threads) {
- t.join();
- }
- }
- // 创建count个线程,每个线程都是不同的jedis连接以及不同的与时间服务器的连接
- private List<Thread> createThreads(int count) throws IOException {
- List<Thread> threads = new ArrayList<Thread>();
- for (int i = 0; i < count; i++) {
- Jedis jedis = new Jedis("localhost", 6379);
- ReentrantLock lock = new ReentrantLock(jedis, LOCK_KEY, EXPIRES, TIME_SERVER_ADDR);
- Task task = new Task(lock);
- Thread t = new Thread(task);
- threads.add(t);
- }
- return threads;
- }
- private static class Task implements Runnable {
- private ReentrantLock lock;
- private final int MAX_ENTRANT = 5;
- private final Random random = new Random();
- private static boolean alive = true;
- Task(ReentrantLock lock) {
- this.lock = lock;
- }
- public void run() {
- while (alive) {
- int times = random.nextInt(MAX_ENTRANT);
- doLock(times);
- }
- }
- private void doLock(int times) {
- if (lock.tryLock(5, TimeUnit.SECONDS)) {
- try {
- if (times > 0) {
- doLock(--times);
- }
- } finally {
- if (lock != null) {
- lock.unlock();
- }
- }
- }
- }
- }
- }
测试结果
下面是一部分日志输出:
- 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}
- 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}
- 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}
- 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}
- 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}
- 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}
- 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}
- 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}
- 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}
- 21:09:22.340-[DEBUG] Thread-0 ReentrantLock - Thread-0 unlock(del), lockInfo: null
- 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}
- 21:09:22.341-[DEBUG] Thread-0 ReentrantLock - Thread-0 unlock(del), lockInfo: null
- 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}
- 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}
- 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}
- 21:09:22.345-[DEBUG] Thread-0 ReentrantLock - Thread-0 unlock(del), lockInfo: null
- 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}
- 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}
- 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}
- 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: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}
- 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}
- 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}
- 21:09:22.351-[DEBUG] Thread-3 ReentrantLock - Thread-3 unlock(del), lockInfo: null
- 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}
- 21:09:22.352-[DEBUG] Thread-3 ReentrantLock - Thread-3 unlock(del), lockInfo: null
- 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}
- 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}
- 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}
- 21:09:22.355-[DEBUG] Thread-0 ReentrantLock - Thread-0 unlock(del), lockInfo: null
- 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}
- 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}
- 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}
- 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}
- 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}
- 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}
- 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}
- 21:09:22.362-[DEBUG] Thread-4 ReentrantLock - Thread-4 unlock(del), lockInfo: null
- 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}
- 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}
- 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}
- 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}
- 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}
- 21:09:22.367-[DEBUG] Thread-0 ReentrantLock - Thread-0 unlock(del), lockInfo: null
- 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}
- 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}
- 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}
- 21:09:22.372-[DEBUG] Thread-4 ReentrantLock - Thread-4 unlock(del), lockInfo: null
- 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}
- 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}
- 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}
- 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}
- 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}
- 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}
- 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}
- 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}
- 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}
- 21:09:22.379-[DEBUG] Thread-1 ReentrantLock - Thread-1 unlock(del), lockInfo: null
- 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}
- 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}
- 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}
- 21:09:22.380-[DEBUG] Thread-2 ReentrantLock - Thread-2 unlock(del), lockInfo: null
- 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}
- 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}
- 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}
- 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}
- 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}
- 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实现分布式锁代码实例 分布式锁的必要性 在多线程环境中,资源竞争是一个常见的问题。例如,在一个简单的用户操作中,一个线程修改用户状态,首先在内存中读取用户状态,然后在内存中进行修改,然后...
Java开发基于SpringBoot+WebSocket+Redis分布式即时通讯群聊系统。一个基于Spring Boot + WebSocket + Redis,可快速开发的分布式即时通讯群聊系统。适用于直播间聊天、游戏内聊天、客服聊天等临时性群聊场景。 ...
本文将深入探讨基于Redis的分布式可重入锁及其在Java开发中的应用。 首先,我们需要理解“可重入锁”的概念。可重入锁允许一个线程多次获取同一锁,这是为了防止死锁的发生。在Java中,ReentrantLock是内置的可重入...
本教程将深入探讨如何在SpringBoot应用中实现基于Redis的分布式锁。 首先,Redis之所以常被用作分布式锁的实现,是因为其具有以下优点: 1. **高可用性**:Redis支持主从复制,可以确保在单点故障时仍有服务可用。...
Redisson是基于Redis的Java客户端,它提供了丰富的数据结构和服务,包括分布式锁、信号量、队列、计数器等,极大地扩展了Redis在分布式系统中的应用能力。本篇文章将详细探讨如何使用Redisson实现Redis分布式事务锁...
以下是一个简单的Java示例,展示了如何使用Jedis客户端库来实现Redis分布式锁。 ```java public class RedisLock { private JedisPool jedisPool; public RedisLock(JedisPool jedisPool) { this.jedisPool = ...
Redis中的分布式锁实现通常基于`SETNX`命令或`SET`命令的`nx`与`ex`组合。`SETNX`命令用于设置键值,但如果键已经存在,则不执行任何操作,这可以确保锁的互斥性。`SET key value EX timeout NX`则同时设置了超时...
Java Redis分布式锁的正确实现方式详解 Java Redis分布式锁是指使用Redis实现的分布式锁机制,旨在解决分布式系统中的并发问题。分布式锁有三种实现方式:数据库乐观锁、基于Redis的分布式锁和基于ZooKeeper的...
在实现基于Redis的分布式锁时,通常会用到两个命令:NX(Not eXists)和EX(过期时间)。NX命令确保只有在键不存在时才能被设置,这样可以保证锁的互斥性。EX命令则是用来设置键的过期时间,保证锁可以在一段时间后...
Redisson的分布式锁实现更加完善,支持可重入锁、公平锁、读写锁,还具有锁自动续期功能,避免了因网络延迟导致的锁丢失。使用Redisson创建分布式锁只需几行代码,通过`RLock`接口的`lock()`和`unlock()`方法即可...
### Java基于Redis分布式消息队的报文过滤系统的设计与实现 #### 一、课题背景与研究意义 随着民用航空业的快速发展,特别是近年来各地新建或扩建民用机场的趋势,导致航空报文数量急剧增加。传统的报文处理系统...
Redis作为一款高性能的键值存储系统,常被用作实现分布式锁的工具,而Redisson是基于Redis的Java客户端,提供了丰富的数据结构和服务功能,包括对分布式锁的支持。本文将深入探讨如何使用Redis和Redisson来构建...
### 基于Redis分布式锁实现“秒杀” #### 一、引言 在现代互联网应用中,“秒杀”作为一种常见的促销手段,被广泛应用于电商领域。为了保证系统的稳定性和公平性,在高并发环境下实现秒杀功能时,合理地利用分布式...
接下来,我们将实现基于Redis的分布式锁。分布式锁的主要目的是在多节点环境下确保同一时刻只有一个节点可以执行特定操作。以下是一个简单的分布式锁实现: ```java public class DistributedLock { private ...
分布式代理锁,动态的锁后缀采用ThreadLocal或者参数名获取 锁粒度自定义选择,目前实现基于redis,后续扩展zk等 SpringBoot,默认使用redisson链接redis,可以更改注解参数使用Spring redis工具 key分为:无后缀、...
"java基于jedisLock—redis分布式锁实现示例代码" java基于jedisLock—redis分布式锁实现示例代码主要介绍了jedisLock—redis分布式锁实现示例代码,以下是对标题和描述中所说的知识点的详细说明: 分布式锁是啥?...
本压缩包文件“基于redis的可重入分布式锁、离线条形码生成与校验方案、常见框架使用demo.zip”提供了一系列实用的技术方案,主要涵盖三个方面:Redis实现的可重入分布式锁、离线条形码的生成与校验,以及常见框架的...
在Java开发中,我们可以利用Redis作为分布式锁的实现方式,其高效、轻量级且具备良好的可扩展性。本文将深入探讨如何基于Redis实现分布式方法锁,并分析其工作原理、优势以及应用场景。 **1. Redis分布式锁的概念**...
- **可重入性**:若需要支持锁的可重入性,可以在客户端维护一个计数器,并在每次获取锁时递增,解锁时递减。 - **公平性**:Redis本身并不支持公平锁,但可以通过客户端策略(如队列等待机制)来模拟实现。 ##### ...
除了基本的实现,还有其他高级特性可以考虑,如公平锁(按照请求顺序获取锁)和可重入锁(一个线程可以多次获取同一把锁)。Redisson是一个成熟的Java Redis客户端,它提供了完善的分布式锁实现,包括这些高级特性。...