有没有一种方法可以从java.util.concurrent.locks.ReentrantReadWriteLock $ ReadLock获取java.util.concurrent.locks.ReentrantReadWriteLock对象 [英] Is there a way i can get the java.util.concurrent.locks.ReentrantReadWriteLock object from java.util.concurrent.locks.ReentrantReadWriteLock$ReadLock

查看:110
本文介绍了有没有一种方法可以从java.util.concurrent.locks.ReentrantReadWriteLock $ ReadLock获取java.util.concurrent.locks.ReentrantReadWriteLock对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用

new java.util.concurrent.locks.ReentrantReadWriteLock().readLock()

然后我将方法传递为Lock接口

and then I pass to a method as Lock interface

method(Lock lock)

现在,我想查找当前线程拥有多少个读取锁.我该如何实现?

Now I want to find how many readlocks are possessed by the current thread. How can i achieve this?

我无法再次将其转换为ReentrantReadWriteLock.我该怎么办?我如何获得此计数?

I can't cast it again into ReentrantReadWriteLock . What should I do? How I can get this count?

推荐答案

要获取ReentrantReadWriteLock上的读取锁计数,您需要调用lock.getReadHoldCount()

To get the read lock count on the ReentrantReadWriteLock, you need to call lock.getReadHoldCount()

要单独从ReadLock中获取此信息,您需要获取同步"字段并通过反射调用"getReadHoldCount()".

To get this from the ReadLock alone, you need to get the "sync" field and call "getReadHoldCount()" via reflection.

使用反射来访问锁的示例如下.

An example of using reflection to access a lock is as follows.

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


您可以做的是创建一个包装器.


What you can do is create a wrapper.

class MyLock implements Lock {
     private final ReentrantReadWriteLock underlying; // set in constructor

     public ReentrantReadWriteLock underlying() { return underlying; }
     public void lock() { underlying.readLock().lock(); }
}

这篇关于有没有一种方法可以从java.util.concurrent.locks.ReentrantReadWriteLock $ ReadLock获取java.util.concurrent.locks.ReentrantReadWriteLock对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆