void
void

Reputation: 761

Stamped lock clarification. Java

Am I right that the sole difference between these two methods for acquiring a lock of StampedLock:

  stampedLock.readLock();
  stampedLock.tryOptimisticRead();

Is that when read lock is held at least by one thread, write lock can't take it; whereas optimistic read allows for write lock to be acquired?

Upvotes: 1

Views: 714

Answers (1)

George Lee
George Lee

Reputation: 826

Basically, yes.

Lots have words have been written on the subject across the internet but I will try and give you brief understanding.


stampedLock.readLock();

Will attempt to obtain a read lock, possibly waiting for a write lock to end. Once you are finished with the read lock you have to unlock using unlockRead(long). The lock is not reentrant. Write locks have to wait for exclusive access, i.e. for all read locks end.


stampedLock.tryOptimisticRead();

Does not lock, but returns a non-zero stamp value that represents the point at which you requested a read. If the value returned is zero the lock is currently in an exclusive write lock, does not wait for the write lock to end. Write locks can be obtained at the same time and perform write actions. Once you have performed your read action you validate that your stamp is still valid via validate(long). If true then a write lock has not been obtained during that period and you are good to continue. Generally speaking, if false you would upgrade to a readLock() an attempt the read again with an actual non-exclusive lock.

Hope this helps. The StampedLock JavaDoc and this article are good places to start reading up.

Upvotes: 2

Related Questions