/** * Locks the specified key in the specified mode. * * @param key the key to lock * @param mode the mode to lock in * @return a lock resource which must be closed to unlock the key * */ public LockResource get(K key, LockMode mode) { ValNode valNode = getValNode(key); ReentrantReadWriteLock lock = valNode.mValue; switch (mode) { case READ: return new RefCountLockResource(lock.readLock(), true, valNode.mRefCount); case WRITE: return new RefCountLockResource(lock.writeLock(), true, valNode.mRefCount); default: throw new IllegalStateException("Unknown lock mode: " + mode); } }
/** * Attempts to take a lock on the given key. * * @param key the key to lock * @param mode lockMode to acquire * @return either empty or a lock resource which must be closed to unlock the key */ public Optional<LockResource> tryGet(K key, LockMode mode) { ValNode valNode = getValNode(key); ReentrantReadWriteLock lock = valNode.mValue; Lock innerLock; switch (mode) { case READ: innerLock = lock.readLock(); break; case WRITE: innerLock = lock.writeLock(); break; default: throw new IllegalStateException("Unknown lock mode: " + mode); } if (!innerLock.tryLock()) { return Optional.empty(); } return Optional.of(new RefCountLockResource(innerLock, false, valNode.mRefCount)); }