Problem: I have a set of Thread
s some of which must take a priority to other in acquiring ReentrantLock
.
The solution: I can imagine to have a fair ReentrantLock
with 2 Condition
queues: lowPriority
and highPriority
. The point is highPriority
is signalled before lowPriority
. Taking into account fairness of ReentrantLock
it must happen that Thread
s blocked in highPriority
always go ahead of Thread
s blocked on lowPriority
.
Implementation:
public class Main {
public static final Lock lock = new ReentrantLock(true);
public static final Condition lowPriority = lock.newCondition();
public static final Condition highPriority = lock.newCondition();
public static boolean cond;
public static void lowPriority() throws InterruptedException {
try {
lock.lock();
while(!cond) {
lowPriority.await();
}
cond = false;
System.out.println("low");
} finally {
lock.unlock();
}
}
public static void highPriority() throws InterruptedException {
try {
lock.lock();
while(!cond) {
highPriority.await();
}
cond = false;
System.out.println("high");
} finally {
lock.unlock();
}
}
public static void setCond(){
try{
lock.lock();
cond = true;
highPriority.signalAll();
lowPriority.signalAll();
} finally {
lock.unlock();
}
}
}
QUESTION: The problem that confused me about the solution is that I could not formally prove from JMM standpoint that as soon as there are Thread
s blocked on highPriority
they always win Thread
s blocked on lowPriority
.
Surely I ran a few experiments and high priority threads always won, but is it formally correct?