I was reading about Java threads and Reentrant Locks. ReentrantLock allow threads to enter into lock on a resource more than once. My question is why does the thread have to do so, if it already has a lock on the resource ? What is the purpose of this "Reentrance" ?
Asked
Active
Viewed 202 times
0
-
Thanks . But I was looking for the purpose of reentrancy rather than how it is implemented. – codechaser Sep 15 '19 at 06:47
-
2The purpose is to avoid deadlock in a situation when a Thread wants to access resource that is guarded by a lock that he is already holding - it was also explained in the duplicate question I linked... – Michał Krzywański Sep 15 '19 at 06:49
-
1If you read the accepted answer you'll find it covers that too. – Boris the Spider Sep 15 '19 at 06:59
1 Answers
2
Suppose there are two state variables in a class:
@GuardedBy("this")
List<String> countryList = new ArrayList<>();
@GuardedBy("this")
Map<String,String> countryCapitalMap = new ArrayList<>();
Suppose some thread A is accessing countryList
. This means that it has acquired the lock on "this". Now since locks are reentrant in Java, it means that the thread would also be able to acquire lock on countryCapitalMap
. If acquiring the lock was per invocation (instead of per thread), then once thread A had acquired the lock on "this", I would have had to release it before it could acquire it again (to access countryCapitalMap
).
Edit: Here's some code:
private synchronized insertCapital(String country, String city) {
this.countryCapitalMap.put(country, city);
}
private synchronized getRandomCountry() {
int randomInt = ...//randomly generated number
return this.countryList.get(randomInt);
}
Reentrant locks would enable your thread to access both of these methods just by acquiring the lock once.

Prashant Pandey
- 4,332
- 3
- 26
- 44
-
You'd be better off writing actual code, rather than just annotating. – Boris the Spider Sep 15 '19 at 06:52
-