出于学术目的,我正在尝试使用低级机制实现类似于Java高级锁的东西。
我想实现一个不同的语义,其中信号器线程必须等到发信号终止其关键区域,但当发出信号终止时,信号器具有优先权以获得锁定。
我怀疑如下:在附加的代码中,存在两个相邻的同步块是一个问题?
我试图解决在同步部分中使用布尔值修改的问题,但由于部分锁定了不同的东西,我不确定这个解决方案。
public class FIFOLock {
private final Queue<QueueElement> entrySet;
private boolean busy;
private Thread owner;
protected Queue<Object> urgentQueue;
public FIFOLock() {
this.entrySet = new LinkedList();
this.urgentQueue = new LinkedList();
this.busy = false;
this.owner = null;
}
public void lock() throws InterruptedException {
QueueElement queued;
synchronized (this) {
if ((owner != null) && (owner.equals(Thread.currentThread())))
return; /* Lock already achieved */
if (!busy) {
busy = true;
this.owner = Thread.currentThread();
System.out.println("LockOwner: " + Thread.currentThread().getName());
// System.out.println("FREE");
return;
}
queued = new QueueElement(true);
entrySet.add(queued);
}
synchronized (queued) {
if (queued.isWaiting())
queued.wait();
this.owner = Thread.currentThread();
}
}
public void unlock() throws InterruptedException {
Object urgentElement = new Object();
QueueElement entryElement = new QueueElement(false);
boolean urgent = false;
synchronized (this) {
if (urgentQueue.size() != 0) {
urgentElement = urgentQueue.poll();
urgent = true;
} else {
if (entrySet.size() == 0) {
busy = false;
return;
}
entryElement = entrySet.poll();
}
}
if (urgent) {
synchronized (urgentElement) {
urgentElement.notify();
}
} else {
synchronized (entryElement) {
owner = null;
if (entryElement.isWaiting())
entryElement.notify();
entryElement.setWaiting(false);
}
}
}
}