aspose file tools
The moose likes Threads and Synchronization and the fly likes Hashmap + Reentrant Locks Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Java » Threads and Synchronization
Reply Bookmark "Hashmap + Reentrant Locks" Watch "Hashmap + Reentrant Locks" New topic
Author

Hashmap + Reentrant Locks

Michael Vargenstien
Ranch Hand

Joined: Jan 27, 2007
Posts: 61
Hello,

I'm trying to understand the behavior of the Reentrant locks classes when used in conjunction with Hashmap. I'm attempting to use the put() method within a lock.writeLock().lock(). So for example:

code starts here
.......
lock.writeLock().lock();
....
someHashmap.put(myValue, yourValue);
...
..
finally {
lock.writeLock().unlock();
}

The write lock is actually used to protect concurrent access to a database.

Also, any good tutorials on this stuff? I've ordered the concurrency in practice book but I'm still waiting for its arrival.

Thanks!
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 16813
    
  19

Reader Writer locks are straightforward. You get either the read lock or the write lock, then you lock it during the section of code where you don't want to be interferred with (ie. no concurrency access to protected store).

In the case of the read lock, you are guaranteed that only threads that also tried to get the read lock could be running. Threads that tries to get the write lock will be blocked.

In the case of the write lock, you are guaranteed that all threads that tries to get the read or write lock would be blocked. You are the only thread that owns the lock.

Of course, this is all cooperative. All threads -- whether reading or writing -- should use the appropiate lock. Another issue to worry about is whether the store will work with concurrent reads. It is probably safe to assume that concurrent reads to a DB should work, but you should confirm it.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Hashmap + Reentrant Locks
 
Similar Threads
synchronized and ReentrantReadWriteLock
Synchronized methods
ReentrantReadWriteLock's lock mechanism
Non-reentrant lock
can a synchronized method block itself ?