0

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" ?

codechaser
  • 91
  • 1
  • 2

1 Answers1

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