• Post Reply Bookmark Topic Watch Topic
  • New Topic

class ReservationsManager  RSS feed

 
Bor Kev
Greenhorn
Posts: 17
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I am preparing for the Oracle Certified Master Java Developer (OCMJD) . I just read Andrew Monkhouse and Terry Camerlengo's book. I am currently running the book's source code but I have a few questions. Below the class I am concerned about.



Well, I looked into the ReentrantLock javadoc but I don't get how the lock mechanism work. I mean I don't see how reserveDVD blocks until the lock succeeds, or for a maximum of 5 seconds, whichever comes first.

I mean at some point when the code states 'lock.lock();' does the thread get the lock or no? also I believe the while (reservations.containsKey(upc)) loop is flawed. Indeed, what happens if one gets the lock before the time limit , I don't see how one get outs of the loop if we get the lock before the time elapses.

Sincerely,

bor_kev
 
Salil Wadnerkar
Ranch Hand
Posts: 90
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you are familiar with "synchronized", then consider that "ReentrantLock" is similar. When a thread calls lock() on a ReentrantLock, it becomes blocked if some other thread already has acquired that lock (using lock()). So, Java guarantees that only one thread will execute the code after the thread acquires a lock and releases it. "await" of "Condition" puts the thread which has the lock in blocked state until some other thread "signal" on that Condition or timeout occurs. The code you posted waits on the condition that "upc" of "reservations" is empty (that is, someone returns the DVD and the that "upc" is no longer reserved (meaning, does not have an entry in "reservations" map). When this condition is satisfied (or timeout occurs, in which case, the thread will not attempt to reserve), the thread will put its reservation for this DVD in the reservations table and give up the lock.
For more information on ReentrantLock and Condition, refer: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/locks/Condition.html
 
Bor Kev
Greenhorn
Posts: 17
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Salil Wadnerkar,

thank you so much for taking the time to explain. It helped very much.

Sincerely,

borkev
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!