Lock锁的基本操作是通过 乐观锁 实现的,由于Lock锁也会在 阻塞 时被 挂起 ,依然属于 悲观锁
synchronized | Lock | |
---|---|---|
实现方式 | JVM层实现 | Java底层代码实现 |
锁的获取 | JVM隐式获取 | lock() / tryLock() / tryLock(timeout, unit) / lockInterruptibly() |
锁的释放 | JVM隐式释放 | unlock() |
锁的类型 | 非公平锁、可重入 | 非公平锁/公平锁、可重入 |
锁的状态 | 不可中断 | 可中断 |
锁的性能 | 高并发下会升级为 重量级锁 | 更稳定 |
public class Point { private double x, y; private final StampedLock lock = new StampedLock(); public void move(double deltaX, double deltaY) { // 获取写锁 long stamp = lock.writeLock(); try { x += deltaX; y += deltaY; } finally { // 释放写锁 lock.unlockWrite(stamp); } } double distanceFromOrigin() { // 乐观读 long stamp = lock.tryOptimisticRead(); // 拷贝变量 double currentX = x, currentY = y; // 判断读期间是否有写操作 if (!lock.validate(stamp)) { // 升级为悲观读 stamp = lock.readLock(); try { currentX = x; currentY = y; } finally { lock.unlockRead(stamp); } } return Math.sqrt(currentX * currentX + currentY + currentY); } }