Charlie berg
Charlie berg

Reputation: 181

what happens when multiple threads want to access a ReentrantReadWriteLock?

When applying a reentrantReadWriteLock, and it is locked, what happens if another thread accesses the Lock while it is already performing another block? (Thus, before it reaches the .unlock)

Is the method canceled out? Or perhaps it's stalled? :O

Upvotes: 0

Views: 1197

Answers (4)

sjlee
sjlee

Reputation: 7896

Since you said ReentrantReadWriteLock, the behavior depends on whether you're talking about taking the read lock or the write lock associated with the ReadWriteLock.

  1. If you're trying to acquire the write lock, you will be blocked until all holders release the lock (whether it is the read lock or the write lock)
  2. If you're trying to acquire the read lock and there is no holder of the write lock, you will always be able to acquire it even if there are other read lock holders
  3. If you're trying to acquire the read lock and there is a holder of the write lock, you will be blocked until the write lock holder releases the write lock

The read lock can be held concurrently by multiple threads as long as there is no writer.

Upvotes: 2

Peter Lawrey
Peter Lawrey

Reputation: 533880

If you don't want to block you can use Lock.tryLock() (which tries without waiting) or tryLock(long time, TimeUnit unit) which will wait only as long as you specify.

Upvotes: 0

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 341003

The thread will block. If more than one thread tries to acquire this lock, all of them will be blocked. When the lock is released, exactly one thread from the waiting pool will acquire the lock and the rest will still wait. See the difference between fair and unfair locks.

Upvotes: 1

Reverend Gonzo
Reverend Gonzo

Reputation: 40871

The thread will block until the lock is available. (docs)

If you only want to acquire the lock if its available, you can use tryLock()

Upvotes: 1

Related Questions