Skip to main content

acquiring writeLock after readLock

5 replies [Last post]
navinkjha
Offline
Joined: 2004-12-28

I recently ran into a issue where a method call acquired readLock and then it had to acquire a writeLock. I followed the documented way, which is call unlock() on read lock and then acquire write lock.

Now if a thread made a call to another method where it acquired read lock and then called the above method it still works.

Now this suggests you can aquire write lock after acquiring read lock as long as it is a different method. Is this a wrong assessment ?

-Navin

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
steevcoco
Offline
Joined: 2004-05-23

Ciao Navin.

Yes, you're assessment [i]should[/i] be wrong according to what you've said is the documented behavior of your locks.

Are you sure that in the "other method" the readLock is not released before it invokes this method?

If you can, post your code. Maybe someone will find out what is going on. You're not using two different locks, right?

If it is acting as you describe, this would be a bug. If you're using java.util.concurrent.locks.ReentrantReadWriteLock then it seems to me that this should deadlock.

navinkjha
Offline
Joined: 2004-12-28

Yes I think I should write a test sample for this. I will do that shortly. For now here is the scenario:

Class A {
private final ReentrantReadWriteLock readWriteLocks = new ReentrantReadWriteLock();
private final Lock readLock = readWriteLocks.readLock();
private final Lock writeLock = readWriteLocks.writeLock();

public void x() {
readLock.lock();
// do something....
y()
readLock.unlock();
}

public void y() {
readLock.lock();
.....
// realize that I need write lock
readLock.unlock();

/* This should not work! coz the thread acquired
the read lock when x() was called and unlock()
in y() decreased the counter only
but it works!
*/
writeLock.lock();
.......
writeLock.unlock();
}
}

christian_schli...
Offline
Joined: 2005-05-21

That would be a violation of the reentrancy.

Have you got a working code sample?

fred34
Offline
Joined: 2004-06-19

as I understand it, write-locks are thread exclusive and the documentation in ReentrantReadWriteLock does say that a read lock cannot be upgraded to a write lock. However, if no other thread currently holds the write lock, then why shouldn't one thread be able to acquire a read lock then a write lock? It simply stops other threads from writing to the data protected by the write lock.

christian_schli...
Offline
Joined: 2005-05-21

No, you can't: Allowing to upgrade from a read lock to a write lock would allow dead locks: Two threads could successfully acquire a read lock first, then try to acquire a write lock, et voi'la: a dead lock instead of a write lock. ;-)

Message was edited by: christian_schlichtherle