1 2 3 4 5 6 7 8 9 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
|
/*******************************************************************************
* Copyright (c) 2008, 2011 IBM Corporation and others
* All rights reserved. This program and the accompanying materials are made
* available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
******************************************************************************/
package org.eclipse.equinox.log.internal;
import java.util.ArrayList;
import java.util.List;
public class BasicReadWriteLock {
private List<Thread> currentReaders = new ArrayList<Thread>(2);
private int writersWaiting = 0;
private Thread writing = null;
public synchronized int readLock() {
while (writing != null || writersWaiting != 0) {
try {
if (writing == Thread.currentThread())
throw new IllegalStateException("Attempted to nest read lock inside a write lock"); //$NON-NLS-1$
wait();
} catch (InterruptedException e) {
// reset interrupted state but keep waiting
Thread.currentThread().interrupt();
}
}
currentReaders.add(Thread.currentThread());
if (currentReaders.size() == 1)
return 1;
Thread current = Thread.currentThread();
int result = 0;
for (Thread reader : currentReaders) {
if (reader == current)
result++;
}
return result;
}
public synchronized void readUnlock() {
currentReaders.remove(Thread.currentThread());
notifyAll();
}
public synchronized void writeLock() {
writersWaiting++;
try {
while (writing != null || currentReaders.size() != 0) {
try {
if (writing == Thread.currentThread() || currentReaders.contains(Thread.currentThread()))
throw new IllegalStateException("Attempted to nest write lock inside a read or write lock"); //$NON-NLS-1$
wait();
} catch (InterruptedException e) {
// reset interrupted state but keep waiting
Thread.currentThread().interrupt();
}
}
} finally {
writersWaiting--;
}
writing = Thread.currentThread();
}
public synchronized void writeUnlock() {
writing = null;
notifyAll();
}
}
|