Tuesday, May 10, 2022

StampedLock With Examples

  StampedLock :  StampedLock was introduced in Java 8. It also supports read and write locks. However, lock acquisition methods return a stamp that will be used to release a lock or to check if the lock is still valid:
public class StampedLock
extends Object
implements Serializable
It also supports both read and write locks. It is a capability-based lock with three modes for controlling read/write access. The state of a StampedLock consists of a version and mode.
  • Writing.
  • Reading.
  • Optimistic Reading.
  • ReadWriteLock use only two mode readLock and writeLock
  • Stampedlock use three mode readLock, writeLock and Optimism lock
  • StampedLocks returns the stamps that are long values which is used to unlock readLock or writeLock.
  • Stampedlock is faster than ReadWriteLock
  • StampedLock Don't like ReadWriteLock, It's not reentrant 
  • StampedLock can convert lock, readLock to writeLock OR writeLock to readLock using tryConvertToReadLock, tryConvertToWriteLock
  • Note that we can convert readLock to writeLock when only single thread acquired readLock using tryConvertToWriteLock. it will not convert to writeLock if multiple thread acquired readLock.
  • writeLock can be converted to readLock using tryConvertToReadLock even we are triying go get multiple writeLock because only one writeLock can be acquired at a time.

public long writeLock() : This is same like ReadWriteLock. It is Exclusively acquires the lock, it is blocking if necessary until available. 

public long tryWriteLock() : Exclusively acquires the lock if it is immediately available.

public long tryWriteLock(long time, TimeUnit unit) : Exclusively acquires the lock if it is available if not available wait for given time. 

public boolean tryUnlockWrite() : Releases the writeLock if it is currently held.

public boolean isWriteLocked() : Return true if the  writeLock is currently held exclusively. 

public long readLock()

public long tryReadLock()

public long tryReadLock(long time, TimeUnit unit)

public long tryUnlockRead()

public long unlock(long stamp)

isReadLocked()

getReadLockCount()

 tryConvertToReadLock : Using tryConvertToReadLock we can convert writeLock to readLock.

tryConvertToWriteLock : Using tryConvertToWriteLock we can convert readLock to writeLock but it can convert to writeLock if only one readLock. if multple readLock is there than it will not convert to writeLock.

tryOptimisticRead()

Exception:

writeLockInterruptibly()

readLockInterruptibly()


Related Tutorials

No comments:

Post a Comment