I need to build what I call an "Unfair Semaphore" with priority.
For example : When a thread with priority = 1
wants to acquire the semaphore, it just has to wait until the other thread with the same priority finished, then it can acquire()
. But when a thread with priority = 2
wants to acquire the semaphore, it has to wait for all threads with priority = 1
to finish before using the semaphore, and then try to acquire()
.
I have a total of 4 different priorities.
Here is what I tried but it didn't work.
Does someone have any solution ?
public class UnfairSemaphore
{
private Semaphore mPrior1;
private Semaphore mPrior2;
private Semaphore mPrior3;
private Semaphore mPrior4;
public UnfairSemaphore()
{
mPrior1 = new Semaphore(1);
mPrior2 = new Semaphore(1);
mPrior3 = new Semaphore(1);
mPrior4 = new Semaphore(1);
}
public void acquire(int priority) throws InterruptedException
{
if(priority == 1)
{
mPrior1.acquire();
}
else if(priority == 2)
{
while(mPrior1.hasQueuedThreads() && mPrior1.availablePermits() <=0)
{
//wait();
}
mPrior2.acquire();
mPrior1.acquire();
}
else if(priority == 3)
{
while(mPrior1.hasQueuedThreads() && mPrior1.availablePermits() <=0 && mPrior2.hasQueuedThreads() && mPrior2.availablePermits() <=0)
{
//wait();
}
mPrior3.acquire();
mPrior2.acquire();
mPrior1.acquire();
}
else
{
while(mPrior1.hasQueuedThreads() && mPrior1.availablePermits() <=0 && mPrior2.hasQueuedThreads() && mPrior2.availablePermits() <=0 && mPrior3.hasQueuedThreads() && mPrior3.availablePermits() <=0)
{
//wait();
}
mPrior4.acquire();
mPrior3.acquire();
mPrior2.acquire();
mPrior1.acquire();
}
}
public void release(int priority)
{
if(priority == 1)
{
mPrior1.release();
}
else if(priority == 2)
{
mPrior1.release();
mPrior2.release();
}
else if(priority == 3)
{
mPrior1.release();
mPrior2.release();
mPrior3.release();
}
else
{
mPrior1.release();
mPrior2.release();
mPrior3.release();
mPrior4.release();
}
//notifyAll();
}
}