Skip to content

Commit

Permalink
使用底层的LockSupport直接完成定时阻塞的功能.
Browse files Browse the repository at this point in the history
  • Loading branch information
yujiasun committed Jun 10, 2016
1 parent 15b842a commit 0d83a7c
Showing 1 changed file with 15 additions and 18 deletions.
33 changes: 15 additions & 18 deletions src/main/java/com/distributed/lock/redis/RedisLockInternals.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;

/**
Expand All @@ -39,25 +40,15 @@ String tryRedisLock(String lockId,long time, TimeUnit unit) {
final long startMillis = System.currentTimeMillis();
final Long millisToWait = (unit != null) ? unit.toMillis(time) : null;
String lockValue=null;
ReentrantLock lock=new ReentrantLock();
try {
lock.lock();
Condition reTryCondition = lock.newCondition();
while (lockValue==null){
lockValue=createRedisKey(lockId);
if(lockValue!=null){
break;
}
if(System.currentTimeMillis()-startMillis-retryAwait>millisToWait){
break;
}
reTryCondition.await(retryAwait, TimeUnit.MILLISECONDS);
while (lockValue==null){
lockValue=createRedisKey(lockId);
if(lockValue!=null){
break;
}
} catch (InterruptedException e) {
log.error(e.getMessage(),e);
Thread.interrupted();
}finally{
lock.unlock();
if(System.currentTimeMillis()-startMillis-retryAwait>millisToWait){
break;
}
LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(retryAwait));
}
return lockValue;
}
Expand Down Expand Up @@ -130,4 +121,10 @@ private String randomId(int size) {
}
return new String(cs);
}

public static void main(String[] args){
System.out.println(System.currentTimeMillis());
LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(300));
System.out.println(System.currentTimeMillis());
}
}

0 comments on commit 0d83a7c

Please sign in to comment.