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;
}
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:
vs
will give different results
you can wrap the returned lock like so