我使用以下命令创建一个java.util.concurrent.locks.ReentrantReadWriteLock
new java.util.concurrent.locks.ReentrantReadWriteLock().readLock()然后我传递给一个方法作为Lock接口
method(Lock lock)现在我想知道当前线程拥有多少读锁。我如何才能做到这一点?
我不能再把它转换成ReentrantReadWriteLock了。我该怎么办?我怎么才能算出这个数字呢?
发布于 2011-11-30 18:22:02
要获取ReentrantReadWriteLock上的读锁计数,需要调用lock.getReadHoldCount()
要仅从ReadLock获取此信息,您需要获取"sync“字段并通过反射调用"getReadHoldCount()”。
使用反射访问锁的示例如下所示。
static void printOwner(ReentrantLock lock) {
try {
Field syncField = lock.getClass().getDeclaredField("sync");
syncField.setAccessible(true);
Object sync = syncField.get(lock);
Field exclusiveOwnerThreadField = AbstractOwnableSynchronizer.class.getDeclaredField("exclusiveOwnerThread");
exclusiveOwnerThreadField.setAccessible(true);
Thread t = (Thread) exclusiveOwnerThreadField.get(sync);
if (t == null) {
System.err.println("No waiter?");
} else {
CharSequence sb = Threads.asString(t);
synchronized (System.out) {
System.out.println(sb);
}
}
} catch (NoSuchFieldException e) {
throw new AssertionError(e);
} catch (IllegalAccessException e) {
throw new AssertionError(e);
}
}你能做的就是创建一个包装器。
class MyLock implements Lock {
private final ReentrantReadWriteLock underlying; // set in constructor
public ReentrantReadWriteLock underlying() { return underlying; }
public void lock() { underlying.readLock().lock(); }
}发布于 2011-11-30 18:35:07
使用ReentrantLock,您可以使用以下命令找出有多少线程正在等待此锁:
ReentrantLock lock = new ReentrantLock();
lock.getQueueLength();
lock.getWaitQueueLength(condition);但是要知道当前线程持有多少读锁,这让我想知道你为什么需要这样的东西?检查您持有的锁的数量对您来说没有多大意义。通常,您应该被允许获取多个读锁并安全地使用它们。
问候你,提比留
https://stackoverflow.com/questions/8324278
复制相似问题