1+ package edu .brown .cs32 .livecode .dispatcher ;
2+
3+ import edu .brown .cs32 .livecode .dispatcher .utils .TABusyException ;
4+ import edu .brown .cs32 .livecode .dispatcher .utils .Utils ;
5+ import edu .brown .cs32 .livecode .records .Student ;
6+ import edu .brown .cs32 .livecode .records .TA ;
7+
8+ import java .util .*;
9+
10+ /**
11+ * A (very incomplete) dispatcher class for TA hours.
12+ */
13+ public class HoursDispatcher {
14+ /** Single queue that the dispatcher will get students from */
15+ private final Deque <Student > queue ;
16+ /** TAs on duty */
17+ private final Map <TA , Integer > minutesLeft = new HashMap <>();
18+ /** How many students have been helped by *any* dispatcher instance. */
19+ static int studentsHelped = 0 ;
20+
21+ /**
22+ * @param signups an Iterator that provides Student objects
23+ */
24+ HoursDispatcher (Deque <Student > signups ) {
25+ this .queue = signups ;
26+ }
27+
28+ /**
29+ * Add an on-duty TA
30+ * @param ta the TA who is arriving for hours
31+ * @param minutes the number of minutes that this TA will stay
32+ */
33+ void addTA (TA ta , int minutes ) {
34+ minutesLeft .put (ta , minutes );
35+ }
36+
37+ /**
38+ * Running this method starts the dispatcher.
39+ */
40+ public void dispatch () {
41+ System .out .println (Utils .timestamp ()+
42+ " Dispatcher: Welcome to edu.brown.cs32.livecode hours!" );
43+
44+ // Loop forever: new students may arrive over time
45+ while (true ) {
46+ // Is there a student waiting right now?
47+ if (queue .peek () != null ) {
48+ // Who will help this student?
49+ // TODO: later, prioritize free TAs with a specialty matching the student's question.
50+ Optional <TA > maybeHelper = this .minutesLeft .keySet ().stream ().filter (TA ::isFree ).findFirst ();
51+ if (maybeHelper .isEmpty ()) {
52+ Utils .tryWait (); // nobody is free; wait a short time
53+ continue ;
54+ }
55+ TA helper = maybeHelper .orElseThrow ();
56+
57+ // Who to see next?
58+ Student nextStudent = queue .poll ();
59+
60+ // Help the student
61+ System .out .println (Utils .timestamp ()+" Dispatcher: Hi " +nextStudent +"; you'll be seen by " +helper );
62+ try {
63+ helper .seeStudent (nextStudent );
64+ } catch (TABusyException e ) {
65+ // We hope this won't happen, but if this class had a bug in it, or a different
66+ // thread were possibly assigning students, or if we had implemented a TA timeout,
67+ // this would be possible...
68+ System .out .println ("Unexpected behavior: TA became busy while assigning student! Re-adding student to queue." );
69+ queue .addFirst (nextStudent ); // a Deque lets us add at the front or the back
70+
71+ }
72+ } else {
73+ System .out .println (Utils .timestamp ()+" Dispatcher (" +studentsHelped +" helped so far): Nobody waiting in queue, will check again shortly." );
74+ Utils .tryWait ();
75+ }
76+ }
77+ }
78+
79+ public static void helpedAStudent () {
80+ studentsHelped ++;
81+ }
82+
83+ }
0 commit comments