r/javahelp • • Oct 09 '15

Having trouble using the ReentrantReadWriteLock

I seem to be having trouble getting ReentrantReadWriteLock to work. I have done it as far as I can tell, correctly, but my audit method seems to be happening during the move method resulting in inconsistent values. From my understanding this should not be happening because a read lock should wait until the write lock has released. Any insight would be very appreciated!

http://pastebin.com/cunmCC4m

5 Upvotes

6 comments sorted by

View all comments

Show parent comment

2

u/[deleted] Oct 09 '15

I'm saying that if you want your calls to run in perfect sequence, like :

transaction

audit

transaction

audit

etc, then you have to hold the lock. If you release and reacquire then it may run in other sequences, e.g.

transaction

transaction

audit

transaction

transaction

audit

audit

audit

In the code you posted you still have no control over this detail:

w.unlock();
r.lock();

Timer interrupts in the processor may occur at any time, even in the middle between those two calls. However, if you invert their order,

r.lock();
w.unlock();

Then you're sure that no other transaction can start until the current one has been audited.

http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReentrantReadWriteLock.html

  • Lock downgrading

Reentrancy also allows downgrading from the write lock to a read lock, by acquiring the write lock, then the read lock and then releasing the write lock.

If you don't care about the ordering of transactions and audits then, of course, you can ignore the whole thing.

2

u/feralalien Oct 09 '15

Ooooh! Interesting, I had seen the bit about downgrading but I didn't understand what it was for. Wow, thank you so much.