25,985
社区成员
发帖
与我相关
我的任务
分享
/* */
/* */ public class JedisLock
/* */ {
/* */ RedisProxy jedis;
/* */ String lockKey;
/* 20 */ int expireMsecs = 60000;
/* */
/* 25 */ int timeoutMsecs = 10000;
/* */
/* 27 */ boolean locked = false;
/* */
/* */ public JedisLock(RedisProxy jedis, String lockKey)
/* */ {
/* 37 */ this.jedis = jedis;
/* 38 */ this.lockKey = lockKey;
/* */ }
/* */
/* */ public JedisLock(RedisProxy jedis, String lockKey, int timeoutMsecs)
/* */ {
/* 51 */ this(jedis, lockKey);
/* 52 */ this.timeoutMsecs = timeoutMsecs;
/* */ }
/* */
/* */ public JedisLock(RedisProxy jedis, String lockKey, int timeoutMsecs, int expireMsecs)
/* */ {
/* 67 */ this(jedis, lockKey, timeoutMsecs);
/* 68 */ this.expireMsecs = expireMsecs;
/* */ }
/* */
/* */ public String getLockKey()
/* */ {
/* 75 */ return this.lockKey;
/* */ }
/* */
/* */ public synchronized boolean acquire()
/* */ throws InterruptedException
/* */ {
/* 87 */ return acquire(this.jedis);
/* */ }
/* */
/* */ public synchronized boolean acquire(RedisProxy jedis)
/* */ throws InterruptedException
/* */ {
/* 99 */ int timeout = this.timeoutMsecs;
/* 100 */ while (timeout >= 0) {
/* 101 */ long expires = System.currentTimeMillis() + this.expireMsecs + 1L;
/* 102 */ String expiresStr = String.valueOf(expires);
/* */
/* 104 */ if (jedis.setnx(this.lockKey, expiresStr).longValue() == 1L)
/* */ {
/* 106 */ this.locked = true;
/* 107 */ return true;
/* */ }
/* */
/* 110 */ String currentValueStr = jedis.get(this.lockKey);
/* 111 */ if ((currentValueStr != null) && (Long.parseLong(currentValueStr) < System.currentTimeMillis()))
/* */ {
/* 115 */ String oldValueStr = jedis.getSet(this.lockKey, expiresStr);
/* */
/* 118 */ if ((oldValueStr != null) && (oldValueStr.equals(currentValueStr)))
/* */ {
/* 121 */ this.locked = true;
/* 122 */ return true;
/* */ }
/* */ }
/* 125 */ timeout -= 100;
/* 126 */ Thread.sleep(100L);
/* */ }
/* 128 */ return false;
/* */ }
/* */
/* */ public synchronized void release()
/* */ {
/* 135 */ release(this.jedis);
/* */ }
/* */
/* */ public synchronized void release(RedisProxy jedis)
/* */ {
/* 142 */ if (this.locked) {
/* 143 */ jedis.del(this.lockKey);
/* 144 */ this.locked = false;
/* */ }
/* */ }
/* */ }
if(System.nanoTime()-begin<workTime) {
if (myLock.del(channelType) == 1L) {
System.out.println("释放锁成功");
} else {
System.out.println("释放锁失败");
}
}
其中workTime就是redis设置key时候的生存时间
所以发现超时了,此时肯定key不会有了,如果有也不是自己的,所以不能删除
这样B线程的key就不会被A删掉
你要说从A判断超时时间点到删除操作时间点之间刚好key失效而B又抢占了的话
只能说这种几率十分少 而且目前并没有绝对完美的解决办法