Here is a simple, no-frills answer. This is similar to how a read / write lock works, except that each locker has exclusive access (usually all readers go in parallel). Note that he does not use Semaphore , because this is almost always the wrong design.
public class PrioLock { private boolean _locked; private boolean _priorityWaiting; public synchronized void lock() throws InterruptedException { while(_locked || _priorityWaiting) { wait(); } _locked = true; } public synchronized void lockPriority() throws InterruptedException { _priorityWaiting = true; try { while(_locked) { wait(); } _locked = true; } finally { _priorityWaiting = false; } } public synchronized void unlock() { _locked = false; notifyAll(); } }
You would use it as one of the Lock types in java.util.concurrent:
Common topics:
_prioLock.lock(); try {
"A priority":
_prioLock.lockPriority(); try { // ... use resource here ... } finally { _prioLock.unlock(); }
UPDATE:
Response to comment regarding “proactive” thread interactions:
In a general sense, you cannot do this. you could create custom functionality that added “pause points” to the locked section that would allow a low priority stream to get a high priority stream, but this would be fraught with danger.
The only thing you could really do is to interrupt the workflow by forcing it to exit the blocked code block (provided that your working code responds to the interrupt). This would allow the high priority thread to accelerate due to the loss of the downstream of the downstream (and you might also need to implement rollback logic).
to implement this you need:
- write "current thread" when the lock succeeds.
- in
lockPriority() , abort the "current thread" if it is found. - implement logic between calls to
lock() / unlock() (low priority) to:- It responds to interruption in a reasonable amount of time.
- it implements any necessary "rollback" code upon interruption
- potentially implement the retry logic outside of
lock() / unlock() calls (low priority) to re-execute any work lost during interruption
jtahlborn
source share