winflex / distributedlock Goto Github PK
View Code? Open in Web Editor NEWDistributed Lock programmed in Java
Distributed Lock programmed in Java
if (isTimeExpired(currLockInfo.getExpires()))
运行过程中异常中断,redis中会有一条锁记录,当程序重新启动后,多个线程会争抢锁,导致锁异常。
LockInfo currLockInfo = LockInfo.fromString(currLockInfoJson);
// 竞争条件只可能出现在锁超时的情况, 因为如果没有超时, 线程发现锁并不是被自己持有, 线程就不会去动value
if (isTimeExpired(currLockInfo.getExpires())) {
// 锁超时了
LockInfo oldLockInfo = LockInfo.fromString(jedis.getSet(lockKey, newLockInfoJson));
if (oldLockInfo != null && isTimeExpired(oldLockInfo.getExpires())) {
// 成功获取到锁, 设置相关标识
logger.debug("{} get lock(new), lockInfo: {}", Thread.currentThread().getName(), newLockInfoJson);
locked = true;
return true;
}
} else {
// 锁未超时, 不会有竞争情况
if (isHeldByCurrentThread(currLockInfo)) { // 当前线程持有
// 成功获取到锁, 设置相关标识
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;
}
}
if (isTimeExpired(currLockInfo.getExpires())) {
// 锁超时了
LockInfo oldLockInfo = LockInfo.fromString(jedis.getSet(lockKey, newLockInfoJson));
//,这里需要判断redis所内容是否为当前锁,要不然并发情况会被多个线程获得锁
//String newSetLockInfoJson = redisTemplate.opsForValue().get(lockKey);
//if (oldLockInfo != null && isTimeExpired(oldLockInfo.getExpires()) &&
//newSetLockInfoJson.equals(newLockInfoJson)) {
if (oldLockInfo != null && isTimeExpired(oldLockInfo.getExpires())) {
// 成功获取到锁, 设置相关标识
logger.debug("{} get lock(new), lockInfo: {}", Thread.currentThread().getName(), newLockInfoJson);
locked = true;
return true;
}
}
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.