• Post Reply Bookmark Topic Watch Topic
  • New Topic

Andrews book: Lock question

 
Harish Yerneni
Ranch Hand
Posts: 94
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ranchers:

How do I know on which object the lock is being attained on(see the bolded code). The book says lock is attained on recordNumbers HashMap. In multithreaded programming, I am used to the code synchronized(<objName> .

public DVD getDvd(String upc) throws IOException {
log.entering("DvdFileAccess", "getDvd", upc);

recordNumbersLock.readLock().lock();
try {
// Determine where in the file this record should be.
// note: if this is null the record does not exist
Long locationInFile = recordNumbers.get(upc);
return (locationInFile != null) ? retrieveDvd(locationInFile)
: null;
} finally {
recordNumbersLock.readLock().unlock();
log.exiting("DvdFileAccess", "getDvd");
}
}

Also, in retrievDVD method, is "DELETED" written in the database file if a dvd is deleted?

DVD returnValue = ("DELETED".equals(upc))
? null
: new DVD(upc, name, composer, director, leadActor,
supportingActor, year, copy);

Thanks,

Harish
 
John Stone
Ranch Hand
Posts: 332
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I guess, you can rely only on comments and name of that lock.
The object, which is locked is "recordNumbersLock". You could do the same thing using synchronized block:


You are synchronizing access to "instance" by forcing all threads to acquire "helpInstance"'s monitor first. Using java.util.concurrent.locks is similiar to this scenario -> I don't see any direct link between lock and hashmap.
Any objections?

You can try this experiment: create 2 threads, where one will protect "instance" using java.util.concurrent.locks, and the other thread using synchronized block on that "instance". And you should see, that this is not thread-safe.
 
Harish Yerneni
Ranch Hand
Posts: 94
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, John. As you said, the lock is on the lock object itself.
 
What are you doing? You are supposed to be reading this tiny ad!
the new thread boost feature brings a LOT of attention to your favorite threads
https://coderanch.com/t/674455/Thread-Boost-feature
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!