java8之非重入锁StampedLock ,并发的另一种处理方式

package com.example.demo.config;

import java.util.concurrent.locks.StampedLock;

public class T {

    private double x, y;
    private final StampedLock sl = new StampedLock();

    // an exclusively locked method   独占锁   写互斥
    void move(double deltaX, double deltaY) {
        long stamp = sl.writeLock();
        try {
            x += deltaX;
            y += deltaY;
        } finally {
            sl.unlockWrite(stamp);
        }
    }

    double distanceFromOrigin() { // A read-only method    只读锁
        long stamp = sl.tryOptimisticRead();//返回验证的标记 是占有锁则返回0
        double currentX = x, currentY = y;

//        是占有锁sl.validate(stamp) 返回false,说明发生锁的变化则需要重新获取 重新读取
        if (!sl.validate(stamp)) {
            stamp = sl.readLock();
            try {
                currentX = x;
                currentY = y;
            } finally {
                sl.unlockRead(stamp);
            }
        }
        return Math.sqrt(currentX * currentX + currentY * currentY);
    }
       //升级可以改为以乐观而非读取模式开始
 /**
54              * 转换当前读戳为写戳,即上写锁
55              * 1.写锁戳,直接返回写锁戳
56              * 2.读锁戳且写锁可获得,则释放读锁,返回写锁戳
57              * 3.乐观读戳,当立即可用时返回写锁戳
58              * 4.其他情况返回0
59              */
void moveIfAtOrigin(double newX, double newY) { // upgrade Could instead start with optimistic, not read mode long stamp = sl.readLock(); try { while (x == 0.0 && y == 0.0) { long ws = sl.tryConvertToWriteLock(stamp); if (ws != 0L) { stamp = ws; x = newX; y = newY; break; } else { sl.unlockRead(stamp); stamp = sl.writeLock(); } } } finally { sl.unlock(stamp); } } }

 

上一篇:可优化-PAT (Basic Level) Practice Python解法 1004 成绩排名(和1028类似/sys/数据筛选/未知数量切片存取)


下一篇:Hadoop集群(第10期副刊)_常用MySQL数据库命令