Last active
February 9, 2016 21:46
-
-
Save zhong-j-yu/3ea91194f55d91059789 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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