Exercise: Complex Scenarios
Unqueueing Tails
Easy, right? Now we get to the nasty part: Getting tails back out again!
- If there are any Urgent tails, always send them first. (Don't rotate preference.)
- If there are no other tails available, send a Dismissed tail. (Don't rotate preference.)
- Otherwise, look for tails in your preferred priority, IMPORTANT or REQUESTING. If you have one, return it and rotate the preference.
- If there's nothing in your preferred priority, look in the other priority. (Don't rotate preference.)
- If there are no tails at all, return null. (Don't rotate preference.)
compareTo()
.
Our programmer used a very simple state machine with just three states:
- STATE_IMPORTANT_FIRST (0) — means we're preferring our first IMPORTANT tail.
- STATE_REQUESTING (1) — means we're preferring a REQUESTING tail.
- STATE_IMPORTANT_SECOND (2) — means we're preferring our second IMPORTANT tail.
public class TailQueue {
public Tail get() {
if (queues[Tail.URGENT].isEmpty())
return getNextInRotation();
return dequeue(Tail.URGENT);
} public Tail getNextInRotation() {
switch(state) {
case STATE_IMPORTANT_FIRST:
return get(Tail.IMPORTANT, Tail.REQUESTING, STATE_REQUESTING);
case STATE_REQUESTING:
return get(Tail.REQUESTING, Tail.IMPORTANT, STATE_IMPORTANT_SECOND);
case STATE_IMPORTANT_SECOND:
default:
return get(Tail.IMPORTANT, Tail.REQUESTING, STATE_IMPORTANT_FIRST);
}
}
}
public class TailQueue {
private Tail get(int firstChoice, int secondChoice, int nextState) {
if (!queues[firstChoice].isEmpty()) {
state = nextState;
return dequeue(firstChoice);
}
if (!queues[secondChoice].isEmpty())
return dequeue(secondChoice); if (!queues[Tail.DISMISSED].isEmpty())
return dequeue(Tail.DISMISSED); return null;
} private Tail dequeue(int queueNumber) {
Tail result = (Tail)queues[queueNumber].first();
queues[queueNumber].remove(result);
return result;
}
}
(Reading...)
Formatting Hints:
To format... | use this markup: |
---|---|
source code | {source:lang=java|lineNumbers=false}...{source} (Supported languages: java, cpp, csharp, c, python.) |
bold text | __some text__ |
italicized text | ~~some text~~ |
underlined text | @@some text@@ |
a method or class name | ``myMethod(...)`` |