Skip to content

Instantly share code, notes, and snippets.

@zhong-j-yu
Last active February 9, 2016 21:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhong-j-yu/3ea91194f55d91059789 to your computer and use it in GitHub Desktop.
Save zhong-j-yu/3ea91194f55d91059789 to your computer and use it in GitHub Desktop.
import java.util.LinkedList;
import java.util.TreeMap;
import java.util.concurrent.locks.LockSupport;
public class UnfairSemaphore
{
TreeMap<Integer, LinkedList<Thread>> waitingThreads = new TreeMap<>();
void storeWaitingThread(Integer priority, Thread thread)
{
LinkedList<Thread> queue = waitingThreads.computeIfAbsent(priority, p->new LinkedList<>());
queue.addLast(thread);
}
// select and remove a waiting thread with highest priority; return null if none.
Thread selectWaitingThread()
{
for(LinkedList<Thread> queue : waitingThreads.values()) // ascending order
if(!queue.isEmpty())
return queue.removeFirst();
return null;
}
// ---------------------------------------------------------------------------------
final Object lock = new Object();
volatile Thread owningThread;
public void acquire(int priority)
{
Thread thisThread = Thread.currentThread();
synchronized (lock)
{
if(owningThread==null)
{
owningThread=thisThread;
return;
}
storeWaitingThread(priority, thisThread);
}
while(owningThread!=thisThread)
{
LockSupport.park();
// interrupt ignored. // todo handle interrupt
}
}
public void release()
{
synchronized (lock)
{
Thread nextOwner = selectWaitingThread();
owningThread = nextOwner;
}
LockSupport.unpark(owningThread);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment