Kevin Qu
Kevin Qu

Reputation: 107

How to use ReadWriteLock

I have a bufferPool which stores a lot of objects. In order to prevent different threads writing the same object and at the same for efficiency I use ReadWriteLock. But I am not too sure about how it works. After I find the object I want to access,

if(perm.equals(Permissions.READ_ONLY)) {                    
  readLock.lock();
} else if(Permissions.READ_WRITE) {                 
  writeLock.lock(); 
}
return the object I want to access

How does the system know which object the program is trying to access and lock it? Or my syntax here is wrong? Help!!! Thanks

Upvotes: 0

Views: 1367

Answers (2)

Matt
Matt

Reputation: 11805

The system doesn't know what you're trying to lock. If you want to use lock objects for a series of items, you'll have to have a lock for each item, or use one lock for the entire object set (which could be a big bottleneck). This is an example where a single lock is used to synchronize access.

// You'll need to create this somewhere else, in your constructor
// or some other routine that gets called once.
ReentrantLock lock = new ReentrantLock(); 


// Then when you want to access:
lock.lock();
try {
 ... // do stuff with the data
}
finally {
  lock.unlock();
}

Upvotes: 1

nsfyn55
nsfyn55

Reputation: 15353

I son't know of any WriteReadLock in java so I'll assume you're talking about ReadWriteLock, First ReadWriteLock is just an interface. You need to declare an implementation like ReentrantReadWriteLock somewhere. It is this instance that maintains the non-exclusive read lock and the exclusive write lock.

The lock instance is what the runtime grabs a monitor on. Look at the implementation its just some fanciness over top of regular old wait(),notify(), and notifyall(). You call in to get the lock instance. you call lock() when you start and unlock() when your done.

Besides that it is best practice to use locks in try-catch-finally with the unlock in the finally to ensure that it will get unlocked no matter what.

Upvotes: 0

Related Questions