- 01
- 02
- 03
- 04
- 05
- 06
- 07
- 08
- 09
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
public class PLock {
private Map<Thread, Integer> readLocks = new HashMap<Thread, Integer>();
private Thread writeLock = null;
private int writeLockCount = 0;
public synchronized void getReadLock() {
Thread currentThread = Thread.currentThread();
long startTimeMillis = System.currentTimeMillis();
boolean gotStuck = false;
while (canClaimReadLock(currentThread) == false) {
gotStuck = true;
try {
wait();
} catch (InterruptedException ex) {
Log.warn("Interrupted while attempting to get read lock.", ex);
}
}
report(gotStuck, startTimeMillis, "read");
if (readLocks.containsKey(currentThread)) {
readLocks.put(currentThread, 1 + readLocks.get(currentThread));
} else {
readLocks.put(currentThread, 1);
}
}
...
public synchronized void relinquishReadLock() {
Thread currentThread = Thread.currentThread();
if (readLocks.containsKey(currentThread) == false) {
throw new RuntimeException("Cannot relinquish read lock on thread " + currentThread + " because it does not hold a lock.");
}
int newLockCount = readLocks.get(currentThread) - 1;
if (newLockCount == 0) {
readLocks.remove(currentThread);
notifyAll(); // IMPORTANT: allow other threads to wake up and check if they can get locks now.
} else {
readLocks.put(currentThread, newLockCount);
}
}
public synchronized void getWriteLock() {
//Log.warn("getWriteLock() in thread " + Thread.currentThread());
//dumpLocks();
Thread currentThread = Thread.currentThread();
long startTimeMillis = System.currentTimeMillis();
boolean gotStuck = false;
while (canClaimWriteLock(currentThread) == false) {
gotStuck = true;
try {
wait();
} catch (InterruptedException ex) {
Log.warn("Interrupted while attempting to get write lock.", ex);
}
}
report(gotStuck, startTimeMillis, "write");
writeLock = currentThread;
writeLockCount++;
}
...
public synchronized void relinquishWriteLock() {
//Log.warn("relinquishWriteLock() in thread " + Thread.currentThread());
Thread currentThread = Thread.currentThread();
if (writeLock != currentThread) {
throw new RuntimeException("Cannot relinquish write lock on thread " + currentThread + " because it does not hold the lock.");
}
if (writeLockCount <= 0) {
throw new RuntimeException("Tried to relinquish write lock on thread " + currentThread + " while write lock count is " + writeLockCount);
}
writeLockCount--;
if (writeLockCount == 0) {
writeLock = null;
notifyAll(); // IMPORTANT: allow other threads to wake up and check if they can get locks now.
}
}
...
}