gpt4 book ai didi

java - 我如何将 ReentrantReadWriteLock.readLock 或 ReentrantReadWriteLock.writeLock 转换为我的类对象

转载 作者:太空宇宙 更新时间:2023-11-04 08:26:54 30 4
gpt4 key购买 nike

我想做的是获取当前线程一次保存的readcounts数量。我为此编写了一个包装器,但我的问题是ReadLock()方法返回ReentrantReadWriteLock.WriteLock,所以我之后没有多余的getThreadReadLockCount。我想要的是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;
}

最佳答案

您的代码仅计算线程请求读锁的次数,如果在锁定和释放之间缓存它,则会给出不同的结果:

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();
}

}
}

关于java - 我如何将 ReentrantReadWriteLock.readLock 或 ReentrantReadWriteLock.writeLock 转换为我的类对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8325864/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com