In my application I am attempting to queue outgoing messages by the following rules
- By default they should be sent no less than
messageDelay
apart - Some messages can be sent immediately, completely bypassing all queued messages
- Additionally, some immediately sent messages can reset the waiting time of queued messages
If this is confusing, this is what it would look like on the wire
| Normal |Immediate |Immediate-reset|
M----------M---M------M----M----------M ....
This was originally handled by a dedicated OutputThread and queue but for various reasons outside of the scope of this question I am attempting to implement this with ReentrantLock and Condition so when any of the methods finally returns, the message is known to of been sent (or an Exception is thrown meaning it didn't)
However this is my first time using ReentrantLock and while I think I've implemented it correctly I'm needing someone to verify that its correct since this is an extremely difficult thing to test
protected final ReentrantLock writeLock = new ReentrantLock(true);
protected final Condition writeNowCondition = writeLock.newCondition();
public void sendRawLine(String line) {
//[Verify state code]
writeLock.lock();
try {
sendRawLineToServer(line);
//Block for messageDelay. If rawLineNow is called with resetDelay
//the condition is tripped and we wait again
while (writeNowCondition.await(getMessageDelay(), TimeUnit.MILLISECONDS)) {
}
} catch (Exception e) {
throw new RuntimeException("Couldn't pause thread for message delay", e);
} finally {
writeLock.unlock();
}
}
public void rawLineNow(String line, boolean resetDelay) {
//[Verify state code]
writeLock.lock();
try {
sendRawLineToServer(line);
if (resetDelay)
//Reset the
writeNowCondition.signalAll();
} finally {
writeLock.unlock();
}
}
Is this the correct way to implement ReentrantLock based on my requirements above? Is there a better way (NOT USING THREADS) to do this?
Exception
... It is very broad, and do not forget that it also captures allRuntimeException
s (therefore including NPE, etc) – fge Jun 20 '13 at 4:43