Is there a way i can get the java.util.concurrent.locks.ReentrantReadWriteLock object from java.util.concurrent.locks.ReentrantReadWriteLock$ReadLock

让人想犯罪 __ 提交于 2019-12-11 05:34:20

问题


I create a java.util.concurrent.locks.ReentrantReadWriteLock using

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

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?

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


回答1:


To get the read lock count on the ReentrantReadWriteLock, you need to call lock.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(); }
}



回答2:


With ReentrantLock you can find out how many threads are waiting for this lock, by using:

ReentrantLock lock = new ReentrantLock();
lock.getQueueLength();
lock.getWaitQueueLength(condition);

But to know how many read locks are held by the current thread, makes me wonder why you need such thing? It doesn't make much sense for you to check how many locks you hold.. Generally, you should be allowed to acquire several read locks and use them safely..

Regards, Tiberiu



来源:https://stackoverflow.com/questions/8324278/is-there-a-way-i-can-get-the-java-util-concurrent-locks-reentrantreadwritelock-o

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!