Why there is no way to check if current thread holds the read lock of ReentrantReadWriteLock?
Asked Answered
E

2

9

I found that the write lock of the ReentrantReadWriteLock provides an isHeldByCurrentThread() method to check whether the invoking thread holds that lock.

But there is no corresponding isHeldByCurrentThread() method for the read lock. Why not?

Edam answered 18/12, 2012 at 17:20 Comment(0)
P
17

I think the answer is in the comment of Doug Leas that he gave for this issue: https://bugs.java.com/bugdatabase/view_bug?bug_id=6207928.

Doug Lea writes:

The current design and behavior are intentional. Read-locks are normally not defined to have a notion of ownership, so ownership cannot be tested. … The JSR166 EG has received a few requests to optionally support per-thread read-hold tracking. Doing this would significantly increase lock overhead, so would need to be governed by an optional construction parameter. We are looking into it.

Piccadilly answered 18/12, 2012 at 17:21 Comment(1)
Ok, I understood. Nevertheless I expected there was some way to check if the current thread holds the read lock of ReentrantReadWriteLock.Edam
R
3

ReentrantReadWriteLock.getReadHoldCount() seems to do the job.

Renzo answered 2/7, 2013 at 23:43 Comment(2)
as long as your code is not doing reentrant readlocks, this will workDavon
No it doesn't. Assume ThreadA acquired the read lock. The count is now 1. Before ThreadA releases the lock, ThreadB relies on getReadHoldCount() > 0 and enters the "protected" code. Now ThreadA a releases the lock, but ThreadB is still in the protected code. ThreadC comes into play, acquires a write lock, gets it (because reader count is zero), and updates some data. -> ThreadB sees inconsistent data.Sharrisharron

© 2022 - 2024 — McMap. All rights reserved.