Java Code Examples for java.util.concurrent.locks.StampedLock#writeLock()

The following examples show how to use java.util.concurrent.locks.StampedLock#writeLock() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RouteTable.java    From sofa-jraft with Apache License 2.0 6 votes vote down vote up
/**
 * Update configuration of group in route table.
 *
 * @param groupId raft group id
 * @param conf    configuration to update
 * @return true on success
 */
public boolean updateConfiguration(final String groupId, final Configuration conf) {
    Requires.requireTrue(!StringUtils.isBlank(groupId), "Blank group id");
    Requires.requireNonNull(conf, "Null configuration");

    final GroupConf gc = getOrCreateGroupConf(groupId);
    final StampedLock stampedLock = gc.stampedLock;
    final long stamp = stampedLock.writeLock();
    try {
        gc.conf = conf;
        if (gc.leader != null && !gc.conf.contains(gc.leader)) {
            gc.leader = null;
        }
    } finally {
        stampedLock.unlockWrite(stamp);
    }
    return true;
}
 
Example 2
Source File: RouteTable.java    From sofa-jraft with Apache License 2.0 6 votes vote down vote up
/**
 * Update leader info.
 *
 * @param groupId raft group id
 * @param leader  peer of leader
 * @return true on success
 */
public boolean updateLeader(final String groupId, final PeerId leader) {
    Requires.requireTrue(!StringUtils.isBlank(groupId), "Blank group id");

    if (leader != null) {
        // If leader presents, it should not be empty.
        Requires.requireTrue(!leader.isEmpty(), "Empty leader");
    }

    final GroupConf gc = getOrCreateGroupConf(groupId);
    final StampedLock stampedLock = gc.stampedLock;
    final long stamp = stampedLock.writeLock();
    try {
        gc.leader = leader;
    } finally {
        stampedLock.unlockWrite(stamp);
    }
    return true;
}
 
Example 3
Source File: StampedLockTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * interruptible operations throw InterruptedException when write locked and interrupted
 */
public void testInterruptibleOperationsThrowInterruptedExceptionWriteLockedInterrupted() {
    final StampedLock lock = new StampedLock();
    long s = lock.writeLock();

    Action[] interruptibleLockBlockingActions = {
        () -> lock.writeLockInterruptibly(),
        () -> lock.tryWriteLock(Long.MAX_VALUE, DAYS),
        () -> lock.readLockInterruptibly(),
        () -> lock.tryReadLock(Long.MAX_VALUE, DAYS),
        () -> lock.asWriteLock().lockInterruptibly(),
        () -> lock.asWriteLock().tryLock(Long.MAX_VALUE, DAYS),
        () -> lock.asReadLock().lockInterruptibly(),
        () -> lock.asReadLock().tryLock(Long.MAX_VALUE, DAYS),
    };
    shuffle(interruptibleLockBlockingActions);

    assertThrowInterruptedExceptionWhenInterrupted(interruptibleLockBlockingActions);
}
 
Example 4
Source File: StampedLockTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * readLock() succeed only after a writing thread unlocks
 */
public void testReadAfterWriteLock() {
    final StampedLock lock = new StampedLock();
    final CountDownLatch threadsStarted = new CountDownLatch(2);
    final long s = lock.writeLock();
    final Runnable acquireReleaseReadLock = new CheckedRunnable() {
        public void realRun() {
            threadsStarted.countDown();
            long rs = lock.readLock();
            assertTrue(lock.isReadLocked());
            assertFalse(lock.isWriteLocked());
            lock.unlockRead(rs);
        }};
    Thread t1 = newStartedThread(acquireReleaseReadLock);
    Thread t2 = newStartedThread(acquireReleaseReadLock);

    await(threadsStarted);
    waitForThreadToEnterWaitState(t1);
    waitForThreadToEnterWaitState(t2);
    assertTrue(lock.isWriteLocked());
    assertFalse(lock.isReadLocked());
    releaseWriteLock(lock, s);
    awaitTermination(t1);
    awaitTermination(t2);
    assertUnlocked(lock);
}
 
Example 5
Source File: RegionRouteTable.java    From sofa-jraft with Apache License 2.0 5 votes vote down vote up
public void addOrUpdateRegion(final Region region) {
    Requires.requireNonNull(region, "region");
    Requires.requireNonNull(region.getRegionEpoch(), "regionEpoch");
    final long regionId = region.getId();
    final byte[] startKey = BytesUtil.nullToEmpty(region.getStartKey());
    final StampedLock stampedLock = this.stampedLock;
    final long stamp = stampedLock.writeLock();
    try {
        this.regionTable.put(regionId, region.copy());
        this.rangeTable.put(startKey, regionId);
    } finally {
        stampedLock.unlockWrite(stamp);
    }
}
 
Example 6
Source File: RegionRouteTable.java    From sofa-jraft with Apache License 2.0 5 votes vote down vote up
public void splitRegion(final long leftId, final Region right) {
    Requires.requireNonNull(right, "right");
    Requires.requireNonNull(right.getRegionEpoch(), "right.regionEpoch");
    final StampedLock stampedLock = this.stampedLock;
    final long stamp = stampedLock.writeLock();
    try {
        final Region left = this.regionTable.get(leftId);
        Requires.requireNonNull(left, "left");
        final byte[] leftStartKey = BytesUtil.nullToEmpty(left.getStartKey());
        final byte[] leftEndKey = left.getEndKey();
        final long rightId = right.getId();
        final byte[] rightStartKey = right.getStartKey();
        final byte[] rightEndKey = right.getEndKey();
        Requires.requireNonNull(rightStartKey, "rightStartKey");
        Requires.requireTrue(BytesUtil.compare(leftStartKey, rightStartKey) < 0,
            "leftStartKey must < rightStartKey");
        if (leftEndKey == null || rightEndKey == null) {
            Requires.requireTrue(leftEndKey == rightEndKey, "leftEndKey must == rightEndKey");
        } else {
            Requires.requireTrue(BytesUtil.compare(leftEndKey, rightEndKey) == 0, "leftEndKey must == rightEndKey");
            Requires.requireTrue(BytesUtil.compare(rightStartKey, rightEndKey) < 0,
                "rightStartKey must < rightEndKey");
        }
        final RegionEpoch leftEpoch = left.getRegionEpoch();
        leftEpoch.setVersion(leftEpoch.getVersion() + 1);
        left.setEndKey(rightStartKey);
        this.regionTable.put(rightId, right.copy());
        this.rangeTable.put(rightStartKey, rightId);
    } finally {
        stampedLock.unlockWrite(stamp);
    }
}
 
Example 7
Source File: RegionRouteTable.java    From sofa-jraft with Apache License 2.0 5 votes vote down vote up
public boolean removeRegion(final long regionId) {
    final StampedLock stampedLock = this.stampedLock;
    final long stamp = stampedLock.writeLock();
    try {
        final Region region = this.regionTable.remove(regionId);
        if (region != null) {
            final byte[] startKey = BytesUtil.nullToEmpty(region.getStartKey());
            return this.rangeTable.remove(startKey) != null;
        }
    } finally {
        stampedLock.unlockWrite(stamp);
    }
    return false;
}
 
Example 8
Source File: StampedLockTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * tryWriteLock fails if locked
 */
public void testTryWriteLockWhenLocked() {
    final StampedLock lock = new StampedLock();
    long s = lock.writeLock();
    Thread t = newStartedThread(new CheckedRunnable() {
        public void realRun() {
            assertEquals(0L, lock.tryWriteLock());
        }});

    assertEquals(0L, lock.tryWriteLock());
    awaitTermination(t);
    releaseWriteLock(lock, s);
}
 
Example 9
Source File: StampedLockTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * tryReadLock fails if write-locked
 */
public void testTryReadLockWhenLocked() {
    final StampedLock lock = new StampedLock();
    long s = lock.writeLock();
    Thread t = newStartedThread(new CheckedRunnable() {
        public void realRun() {
            assertEquals(0L, lock.tryReadLock());
        }});

    assertEquals(0L, lock.tryReadLock());
    awaitTermination(t);
    releaseWriteLock(lock, s);
}
 
Example 10
Source File: StampedLockTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * A serialized lock deserializes as unlocked
 */
public void testSerialization() {
    StampedLock lock = new StampedLock();
    lock.writeLock();
    StampedLock clone = serialClone(lock);
    assertTrue(lock.isWriteLocked());
    assertFalse(clone.isWriteLocked());
    long s = clone.writeLock();
    assertTrue(clone.isWriteLocked());
    clone.unlockWrite(s);
    assertFalse(clone.isWriteLocked());
}
 
Example 11
Source File: StampedLockTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * toString indicates current lock state
 */
public void testToString() {
    StampedLock lock = new StampedLock();
    assertTrue(lock.toString().contains("Unlocked"));
    long s = lock.writeLock();
    assertTrue(lock.toString().contains("Write-locked"));
    lock.unlockWrite(s);
    s = lock.readLock();
    assertTrue(lock.toString().contains("Read-locks"));
}
 
Example 12
Source File: ForkChainsMonitor.java    From nuls-v2 with MIT License 4 votes vote down vote up
@Override
protected void process(int chainId, ChainContext context, NulsLogger commonLog) {
    StampedLock lock = context.getLock();
    long stamp = lock.tryOptimisticRead();
    try {
        for (; ; stamp = lock.writeLock()) {
            if (stamp == 0L) {
                continue;
            }
            // possibly racy reads
            SortedSet<Chain> forkChains = BlockChainManager.getForkChains(chainId);
            if (!lock.validate(stamp)) {
                continue;
            }
            if (forkChains.isEmpty()) {
                break;
            }
            context.printChains();
            //遍历当前分叉链,与主链进行比对,找出最大高度差,与默认参数chainSwtichThreshold对比,确定要切换的分叉链
            Chain masterChain = BlockChainManager.getMasterChain(chainId);
            ChainParameters parameters = context.getParameters();
            int chainSwtichThreshold = parameters.getChainSwtichThreshold();
            Chain switchChain = new Chain();
            int maxHeightDifference = 0;
            for (Chain forkChain : forkChains) {
                int temp = (int) (forkChain.getEndHeight() - masterChain.getEndHeight());
                if (temp > maxHeightDifference) {
                    maxHeightDifference = temp;
                    switchChain = forkChain;
                }
            }
            commonLog.debug("chainId-" + chainId + ", maxHeightDifference:" + maxHeightDifference + ", chainSwtichThreshold:" + chainSwtichThreshold);
            //高度差不够
            if (maxHeightDifference < chainSwtichThreshold) {
                break;
            }
            stamp = lock.tryConvertToWriteLock(stamp);
            if (stamp == 0L) {
                continue;
            }
            // exclusive access
            //进行切换,切换前变更模块运行状态
            context.setStatus(StatusEnum.SWITCHING);
            ConsensusCall.notice(chainId, MODULE_WAITING);
            TransactionCall.notice(chainId, MODULE_WAITING);
            if (BlockChainManager.switchChain(chainId, masterChain, switchChain)) {
                commonLog.info("chainId-" + chainId + ", switchChain success");
            } else {
                commonLog.info("chainId-" + chainId + ", switchChain fail, auto rollback success");
            }
            context.printChains();
            ConsensusCall.notice(chainId, MODULE_WORKING);
            TransactionCall.notice(chainId, MODULE_WORKING);
            break;
        }
    } finally {
        context.setStatus(StatusEnum.RUNNING);
        if (StampedLock.isWriteLockStamp(stamp)) {
            lock.unlockWrite(stamp);
        }
    }
}
 
Example 13
Source File: OrphanChainsMaintainer.java    From nuls-v2 with MIT License 4 votes vote down vote up
@Override
protected void process(int chainId, ChainContext context, NulsLogger commonLog) {
    ChainParameters parameters = context.getParameters();
    int orphanChainMaxAge = parameters.getOrphanChainMaxAge();

    StampedLock lock = context.getLock();
    long stamp = lock.tryOptimisticRead();
    try {
        for (; ; stamp = lock.writeLock()) {
            if (stamp == 0L) {
                continue;
            }
            // possibly racy reads
            SortedSet<Chain> orphanChains = BlockChainManager.getOrphanChains(chainId);
            if (!lock.validate(stamp)) {
                continue;
            }
            if (orphanChains.isEmpty()) {
                break;
            }
            stamp = lock.tryConvertToWriteLock(stamp);
            if (stamp == 0L) {
                continue;
            }
            // exclusive access
            List<Node> availableNodes = NetworkCall.getAvailableNodes(chainId);
            //维护现有孤儿链,尝试在链首增加区块
            context.setStatus(UPDATE_ORPHAN_CHAINS);
            long l = System.nanoTime();
            for (Chain orphanChain : orphanChains) {
                maintainOrphanChain(chainId, orphanChain, availableNodes, orphanChainMaxAge);
                //孤儿链维护时间超过十秒,就退出
                if (System.nanoTime() - l > 10000000000L) {
                    break;
                }
            }
            break;
        }
    } finally {
        context.setStatus(RUNNING);
        if (StampedLock.isWriteLockStamp(stamp)) {
            lock.unlockWrite(stamp);
        }
    }
}
 
Example 14
Source File: StorageSizeMonitor.java    From nuls-v2 with MIT License 4 votes vote down vote up
/**
 * 清理分叉链
 *
 * @param chainId
 * @param heightRange
 * @param context
 */
private void forkChainsCleaner(int chainId, int heightRange, ChainContext context) {
    StampedLock lock = context.getLock();
    long stamp = lock.tryOptimisticRead();
    NulsLogger logger = context.getLogger();
    try {
        for (; ; stamp = lock.writeLock()) {
            if (stamp == 0L) {
                continue;
            }
            // possibly racy reads
            //1.清理链起始高度位于主链最新高度增减30(可配置)范围外的分叉链
            SortedSet<Chain> forkChains = BlockChainManager.getForkChains(chainId);
            if (!lock.validate(stamp)) {
                continue;
            }
            if (forkChains.isEmpty()) {
                break;
            }
            stamp = lock.tryConvertToWriteLock(stamp);
            if (stamp == 0L) {
                continue;
            }
            // exclusive access
            Chain masterChain = BlockChainManager.getMasterChain(chainId);
            long latestHeight = masterChain.getEndHeight();
            SortedSet<Chain> deleteSet = new TreeSet<>(Chain.COMPARATOR);
            //1.标记
            for (Chain forkChain : forkChains) {
                if (latestHeight - forkChain.getStartHeight() > heightRange || masterChain.getHashList().contains(forkChain.getEndHash())) {
                    //清理orphanChain,并递归清理orphanChain的所有子链
                    deleteSet.add(forkChain);
                }
            }
            //2.清理
            for (Chain chain : deleteSet) {
                BlockChainManager.deleteForkChain(chainId, chain, true);
                logger.info("remove fork chain, chain:" + chain);
            }
            break;
        }
    } finally {
        if (StampedLock.isWriteLockStamp(stamp)) {
            lock.unlockWrite(stamp);
        }
    }
}
 
Example 15
Source File: StorageSizeMonitor.java    From nuls-v2 with MIT License 4 votes vote down vote up
/**
 * 清理孤儿链
 * @param chainId
 * @param heightRange
 * @param context
 * @param orphanChainMaxAge
 */
private void orphanChainsCleaner(int chainId, int heightRange, ChainContext context, int orphanChainMaxAge) {
    StampedLock lock = context.getLock();
    long stamp = lock.tryOptimisticRead();
    NulsLogger logger = context.getLogger();
    try {
        for (; ; stamp = lock.writeLock()) {
            if (stamp == 0L) {
                continue;
            }
            // possibly racy reads
            //1.清理链起始高度位于主链最新高度增减30(可配置)范围外的孤儿链
            SortedSet<Chain> orphanChains = BlockChainManager.getOrphanChains(chainId);
            if (!lock.validate(stamp)) {
                continue;
            }
            if (orphanChains.isEmpty()) {
                break;
            }
            stamp = lock.tryConvertToWriteLock(stamp);
            if (stamp == 0L) {
                continue;
            }
            // exclusive access
            Chain masterChain = BlockChainManager.getMasterChain(chainId);
            long latestHeight = masterChain.getEndHeight();
            SortedSet<Chain> deleteSet = new TreeSet<>(Chain.COMPARATOR);
            //1.标记
            for (Chain orphanChain : orphanChains) {
                if (Math.abs(orphanChain.getStartHeight() - latestHeight) > heightRange || orphanChain.getAge().get() > orphanChainMaxAge) {
                    //清理orphanChain,并递归清理orphanChain的所有子链
                    deleteSet.add(orphanChain);
                }
            }
            //2.清理
            for (Chain chain : deleteSet) {
                BlockChainManager.deleteOrphanChain(chainId, chain);
                logger.info("remove orphan chain, chain:" + chain);
            }
            break;
        }
    } finally {
        if (StampedLock.isWriteLockStamp(stamp)) {
            lock.unlockWrite(stamp);
        }
    }
}
 
Example 16
Source File: KeyedLockManager.java    From blazingcache with Apache License 2.0 4 votes vote down vote up
LockID acquireWriteLockForKey(RawString key, String clientId) {
    StampedLock lock = makeLockForKey(key);
    LockID result = new LockID(lock.writeLock());
    return result;
}