我面临着一个关于
StampedLock的奇怪行为.以下是主要有问题的代码行:
StampedLock lock = new StampedLock();
long stamp1 = lock.readLock();
System.out.printf("Read lock count: %d%n", lock.getReadLockCount());
lock.unlock(stamp1 + 2);
System.out.printf("Read lock count: %d%n", lock.getReadLockCount());
奇怪的行为是关于如何解锁“容忍”错误的读取标记.你觉得这样对吗?
这里是参考的完整代码:
public class StampedLockExample {
static StampedLock lock = new StampedLock();
static void println(String message, Object... args) {
System.out.printf(message, args);
System.out.println();
}
static void printReadLockCount() {
println("Lock count=%d", lock.getReadLockCount());
}
static long tryReadLock() {
long stamp = lock.tryReadLock();
println("Gets read lock (%d)", stamp);
printReadLockCount();
return stamp;
}
static long tryWriteLock() {
long stamp = lock.tryWriteLock();
println("Gets write lock (%d)", stamp);
return stamp;
}
static long tryConvertToReadLock(long stamp) {
long newOne = lock.tryConvertToReadLock(stamp);
println("Gets read lock (%d -> %d)", stamp, newOne);
printReadLockCount();
return newOne;
}
static void tryUnlock(long stamp) {
try {
lock.unlock(stamp);
println("Unlock (%d) successfully", stamp);
} catch (IllegalMonitorStateException e) {
println("Unlock (%d) failed", stamp);
}
printReadLockCount();
}
public static void main(String[] args) {
println("%n--- Gets two read locks ---");
long stamp1 = tryReadLock();
long stamp2 = tryReadLock();
long min = Math.min(stamp1, stamp2);
long max = Math.max(stamp1, stamp2);
println("%n--- Tries unlock (-1 / +2 / +4) ---");
tryUnlock(min - 1);
tryUnlock(max + 2);
tryUnlock(max + 4);
println("%n--- Gets write lock ---");
long stamp3 = tryWriteLock();
println("%n--- Tries unlock (-1 / +1) ---");
tryUnlock(stamp3 - 1);
tryUnlock(stamp3 + 1);
println("%n--- Tries write > read conversion ---");
long stamp4 = tryConvertToReadLock(stamp3);
println("%n--- Tries unlock last write stamp (-1 / 0 / +1) ---");
tryUnlock(stamp3 - 1);
tryUnlock(stamp3);
tryUnlock(stamp3 + 1);
println("%n--- Tries unlock (-1 / +1) ---");
tryUnlock(stamp4 - 1);
tryUnlock(stamp4 + 1);
}
}
输出:
--- Gets two read locks ---
Gets read lock (257)
Lock count=1
Gets read lock (258)
Lock count=2
--- Tries unlock (-1 / +2 / +4) ---
Unlock (256) failed
Lock count=2
Unlock (260) successfully
Lock count=1
Unlock (262) successfully
Lock count=0
--- Gets write lock ---
Gets write lock (384)
--- Tries unlock (-1 / +1) ---
Unlock (383) failed
Lock count=0
Unlock (385) failed
Lock count=0
--- Tries write > read conversion ---
Gets read lock (384 -> 513)
Lock count=1
--- Tries unlock last write stamp (-1 / 0 / +1) ---
Unlock (383) failed
Lock count=1
Unlock (384) failed
Lock count=1
Unlock (385) failed
Lock count=1
--- Tries unlock (-1 / +1) ---
Unlock (512) failed
Lock count=1
Unlock (514) successfully
Lock count=0