Is there a limit to the ReentrantReadWriteLock? I'm now testing my application and it seems my write lock isn't giving out locks anymore (returning true: tryLock()
) when I'm at 20 threads.

- 2,268
- 3
- 25
- 51
-
1A *write lock* usually support *at most one* owning thread. And there must be no read lock at the same time. When you have 20 threads using read locks it’s very likely that there is always at least one thread owning a read lock when you do `tryLock` on the write lock. – Holger Apr 25 '14 at 07:59
-
@Holger Good shout. That's probably it! – Martijn Apr 25 '14 at 08:47
2 Answers
The limit is 65535 locks, so it seems unlikely you have hit it with 20 threads. (Although possible, the limit does count re-entrant acquisitions. However, violating it results in an error being thrown, not a false return value from tryLock()
.)
What is more likely is you're at a point where the system is busy enough that it's unlikely for a lock to be available at that exact instant when you attempt tryLock()
. You should probably switch to a call that blocks with a reasonable timeout so that the thread waits until others are done and the lock becomes available.

- 47,174
- 11
- 83
- 83
-
That's the weird part. The lock isn't locked before. This is first time in the app. – Martijn Apr 24 '14 at 21:12
-
-
Self Contained Complete Example: An executable program that demonstrates the problem. (Often trying to reduce the code to the minimum necessary to reproduce the problem leads to discovering the issue as well!) – Affe Apr 24 '14 at 21:35
-
(returning true: tryLock()) when I'm at 20 threads.
Unless you have 20 CPUs, these threads are not running all at the same time, and the threads which are running are likely to be staving out the threads which are not. If you need to avoid this, you have to use a fair lock.
A better solution is to not write code where it is significant contention on any lock.

- 525,659
- 79
- 751
- 1,130
-
A fair lock doesn’t help when all he does is `tryLock`. Only the blocking `lock` call is able to remember how long the thread is waiting. – Holger Apr 25 '14 at 07:55