1

I have this (simplified) scenario:

@Test
public void testSameThread() throws InterruptedException {
    ReentrantReadWriteLock rwlock = new ReentrantReadWriteLock();
    rwlock.readLock().lock();
    {
        if (rwlock.writeLock().tryLock(50, TimeUnit.MILLISECONDS)) {
            // long-running op
            Thread.sleep(100);
            rwlock.writeLock().unlock();
        } else {
            fail();
        }
    }
    rwlock.readLock().unlock();
}

First, I acquire a read lock, then on the SAME thread I try to acquire the write lock. My assumption is that as I am on the same thread, the write lock should be acquired.

First, what is wrong with my assumption? Then, what pattern (standard Java locking mechanism) can be used to allow arbitrary nested read/write locks for the same thread?

erdal.karaca
  • 693
  • 1
  • 4
  • 20
  • You are just making an assumption here and you got a clear answer for it, your question suggest that something is not working as you expect, please add more details to your question, what are the expected and the observed behaviours? What makes you say that it is not working as you expect? – A4L Aug 31 '17 at 06:54

1 Answers1

1

Nothing is wrong with your assumption. In fact it's not an assumption, it's a well documented¹ fact. From ReentrantReadWriteLock.WriteLock.lock():

Acquires the write lock if neither the read nor write lock are held by another thread

It wouldn't be reentrant if it blocked while acquiring multiple times on the same thread.

¹In fact not so well documented after all, see comments section

Kayaman
  • 72,141
  • 5
  • 83
  • 121
  • So, this is a bug in the WriteLock impl? What should I use instead? – erdal.karaca Aug 31 '17 at 06:43
  • Where is the bug in the code (it is not that complex)? – erdal.karaca Aug 31 '17 at 06:45
  • Actually there is a "bug" here, but it's in the form of unclear documentation. `RRWL` allows you to downgrade to a readlock, but for upgrading to a writelock you need to release the readlock first. – Kayaman Aug 31 '17 at 06:54
  • @erdal.karaca Sorry 'bout that. Not a bug per se, but definitely unclear documentation. – Kayaman Aug 31 '17 at 06:56
  • Thanks, you helped understand what to do to make the test pass. I would suggest to also reflect the downgrading aspect in your answer for future reference... – erdal.karaca Aug 31 '17 at 07:04