1

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;
}
user882196
  • 1,691
  • 9
  • 24
  • 39
  • 1
    I would use the approach I suggested to your previous question http://stackoverflow.com/questions/8324278/is-there-a-way-i-can-get-the-java-util-concurrent-locks-reentrantreadwritelock-o – Peter Lawrey Nov 30 '11 at 12:42

1 Answers1

1

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

     }
} 
ratchet freak
  • 47,288
  • 5
  • 68
  • 106