I have a priority queue (with synchronized access) of tasks. Each task has a time at which it is to be performed. When the task at the front of the queue is due to be performed, it should be popped from the queue, but not before since something could be added ahead of it in the queue. (i.e. with an earlier timestamp). Also the task could be removed from the Q before it is due to be performed.
This much I think I have (sudo code)
public synchronized task Q.get(){
while Q.empty(){
wait();
}
// queue is not empty
if (Q.head.time.isBefore(now)){ // task at head of Q is due to be done
return Q.pop();
}else{
// THIS IS WHERE IM STUCK ***
}
At the point *:
I could write code to sleep until the time of the task at the head of the queue, then take it. The problem here would be that we have a lock on the Q and so no tasks can be added while we sleep?? Also if something would be added (though I'm not sure it can) at the head of the queue then the reader would sleep too long.
I also thought I could write code to wait() on the Q again, but after setting a timer (a separate thread owned by the queue purely to Q.notify at the time of the task at the head of the queue). The problem I see with this is that if something is placed at the head of the Q, we'd interrupt the timer and notify on Q then the reader would take the new head task, without checking it's time.
Any help would be really appreciated, thanks in advance. I'm fairly inexperienced with this, so please correct any wrong assumptions etc.
Edit. The reader class, simply loops, gets the next task by calling Q.get() and actions it.