How i can convert ReentrantReadWriteLock.readLock or ReentrantReadWriteLock.writeLock into my class objects

352 Views Asked by At

What I am trying to do is to get the number of readcounts hold by the current thread at a single time.I wrote a wrapper for that but my problem is that ReadLock() method is returning ReentrantReadWriteLock.WriteLock so I have no excess to the getThreadReadLockCount afterwards.What i want is that readLock() method should return me so that I can have excess to the count method. Anyideas.?

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

There are 1 best solutions below

1
On BEST ANSWER

your code only counts how many times a thread requested the readlock, if it is cached between lock and release this will give different results:

Lock rl = var.readLock();
rl.lock();
try{
    //...
}finally{
    rl.unlock();
}

vs

var.readLock().lock();
try{
    //...
}finally{
    var.readLock().unlock();
}

will give different results

you can wrap the returned lock like so

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

     }
}