我想做的是一次获取当前线程持有的读取计数的数量。为此我写了一个包装器,但是我的问题是ReadLock()方法返回的是ReentrantReadWriteLock.WriteLock,所以我没有多余的东西之后我想要的是getLockReadLockCount。我想要的是readLock()方法应该返回我,以便我可以超出count方法。有任何想法吗。?
private final ThreadLocal readLocksHeldByThread;
private static class ReadCounts {
public int value = 0;
}
public CustomReentrantReadWriteLock() {
super(true);
readLocksHeldByThread = new ThreadLocal() {
@Override
public Object initialValue() {
return new ReadCounts();
}
};
}
@Override
public synchronized ReadLock readLock() {
final ReadCounts myReadLocks = (ReadCounts) readLocksHeldByThread.get();
++myReadLocks.value;
return super.readLock();
}
public synchronized int getThreadReadLockCount() {
final ReadCounts currentReadLocks = (ReadCounts) readLocksHeldByThread.get();
return currentReadLocks.value;
}
最佳答案
您的代码仅计算线程请求readlock的次数,如果它在锁和释放之间进行了缓存,则会得出不同的结果:
Lock rl = var.readLock();
rl.lock();
try{
//...
}finally{
rl.unlock();
}
与
var.readLock().lock();
try{
//...
}finally{
var.readLock().unlock();
}
会给出不同的结果
您可以像这样包装返回的锁
@Override public Lock readLock() {
final ReadCounts myReadLocks = (ReadCounts) readLocksHeldByThread.get();
return new Lock(){
Lock l = super.readLock();
public void lock(){
l.lock();
++myReadLocks.value;
}
public void lockInterruptibly() throws InterruptedException{
l.lockInterruptibly();
++myReadLocks.value;
}
public boolean tryLock(){
if(l.tryLock()){
++myReadLocks.value;
return true;
}else return false;
}
public boolean tryLock(long time, TimeUnit unit) throws InterruptedException{
if(l.tryLock(time,unit)){
++myReadLocks.value;
return true;
}else return false;
}
public void unlock(){
--myReadLocks.value;
l.unlock();
}
public Condition newCondition(){
return l.newCondition();
}
}
}