StampedLock 是 Java 8 引入的一种新的锁机制,它是 ReadWriteLock 的改进版,提供了更高的并发性和更好的性能。下面是一个使用 StampedLock 的示例:
import java.util.concurrent.locks.StampedLock;
public class StampedLockDemo {
private double x, y;
private final StampedLock sl = new StampedLock();
// 排它锁-写锁
void move(double deltaX, double deltaY) {
long stamp = sl.writeLock();
try {
x += deltaX;
y += deltaY;
} finally {
sl.unlockWrite(stamp);
}
}
// 乐观读锁
double distanceFromOrigin() {
long stamp = sl.tryOptimisticRead();
double currentX = x, currentY = y;
if (!sl.validate(stamp)) {
stamp = sl.readLock();
try {
currentX = x;
currentY = y;
} finally {
sl.unlockRead(stamp);
}
}
return Math.sqrt(currentX * currentX + currentY * currentY);
}
// 悲观读锁
void moveIfAtOrigin(double newX, double newY) {
// 尝试获取悲观读锁
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);
}
}
}
在上面的示例中,我们使用 StampedLock 来实现一个二维平面上的点,具有移动、计算距离以及在原点处移动等操作。其中,move() 方法使用排它锁(写锁)来保证线程安全;distanceFromOrigin() 方法使用乐观读锁来提高并发性能;moveIfAtOrigin() 方法则使用悲观读锁来保证线程安全并避免死锁。
标签:stamp,double,使用,long,StampedLock,读锁,例子,sl From: https://www.cnblogs.com/sunupo/p/18034417