"Design a traffic signal" sounds like a loop: green, yellow, red, repeat. A weak answer gives each of the four lights its own timer, or writes a Light class with a next() method, and stops. Nothing in that answer stops north and east from being green at the same moment, and that is the one thing a signal must never do.
The interviewer is checking safety first and change second. Two roads that cross must never be green together, and every green must end with a yellow and then a moment of red everywhere. Then the junction has to take things that arrive at any time: a new timing plan for the evening rush, a walker's button, an ambulance that needs a green now, and a lamp that fails. Each of these has to reach the lamps without breaking the first rule.
This article walks through the question the way a 45 minute interview goes. We ask questions, find the classes, then build the design one decision at a time. Every snippet is cut from a complete Java project that compiles and runs. The Open file button on a snippet opens the whole file in a code browser, and the full project is at the end.
Ask before you design
The question is vague on purpose. Each question below changes the code, and the right-hand column says how.
| Question | What we assume | What it changes |
|---|---|---|
| One junction or a whole road? | One junction with four approaches: north, south, east and west | One SignalController, and no links between junctions |
| Which movements? | Straight through only, with no turn arrows | Two vehicle phases, north-south and east-west |
| How do walkers cross? | On their own phase, with all traffic stopped, and only after someone presses the button | A PEDESTRIAN phase that is skipped unless someone is waiting |
| Do green times change? | Yes, by time of day, from a few timing plans | A TimingPlan record, and a rule for when a new one starts |
| Can a plan change yellow or all-red? | No. Those come from the road's width and speed limit | A separate Clearance record, set once |
| What about emergency vehicles? | A detector asks for a green for one approach, and says when the vehicle has passed | preempt and endPreemption |
| What about faults? | A lamp monitor reports one, and the signal flashes red until a technician resets it | reportFault, reset and a flashing interval |
| Are there sensors that count cars? | No. Times come only from the plan | No input apart from the button and the detector |
| What calls the controller? | A one-second timer, the button, the detector, the monitor and the schedule, each on its own thread | One lock, and time that moves only in tick() |
The last question matters most. Five sources call the controller on five threads, and the lamps must stay safe in whatever order the calls arrive. That answer shapes the design: time moves only in tick(), every other call leaves a note for the next tick, and one lock covers both.
Requirements
Functional:
- Two approaches that cross are never green at the same time, and WALK never shows while any vehicle lamp is green or yellow.
- Every green ends with a full yellow and then a full all-red before anything else may go. A walk ends with a full flashing DON'T WALK and then all-red.
- In normal running the phases go north-south, then east-west, then the walk if someone pressed the button. Green times come from the current plan.
- A new plan starts with the next cycle. The cycle in progress keeps the plan it started with.
- A press of the button brings one walk, however many times it is pressed.
- An emergency vehicle gets a green for its approach as soon as the clearance allows, and keeps it until it has passed. One vehicle is served at a time.
- A reported fault takes the signal through the clearance to flashing red, until a technician resets it.
Out of scope: linking several junctions into a green wave, sensors that count cars, turn arrows, two emergency vehicles at once, and keeping state across a power cut. We come back to these at the end.
Everything lives in memory, as is normal for a low-level design interview. The lamps are hardware outside the code. The cabinet reads a SignalView and switches them.
What the code itself must handle:
- Safety by construction. The first rule must follow from how the state is stored, not from a check someone could forget to call.
- Several callers at once. The timer, the button, the detector, the monitor and the schedule each call from their own thread.
- Testable time. A test must be able to step the signal one second at a time, with no sleeping.
Finding the classes
Picking the nouns out of the requirements gives a first list. Most become classes, records or enums. A few are dropped, and dropping them is part of the design.
The noun that needs the most thought is traffic light, because it is the first class most designs write.
Should each traffic light be its own object?
A TrafficLight per approach, each with its own timer
This matches the question's words, and each light is easy to write. But four objects that change on their own can disagree. Keeping north and east apart then needs the lights to watch each other, and every light added brings more pairs to check.
No. One SignalController holds the only state, and a light shows what it is toldOur pick
A light has no behaviour of its own: it shows a colour. The choice of colours belongs in one place that sees the whole junction at once. The cost is that every change goes through one class.
Data or behaviour?
Some types only carry values that never change: what the junction shows, a timing plan, the clearance times, a row of the schedule. In Java these are records. A record's fields are fixed when it is created, and it gets equals, hashCode and toString without writing them. Fixed sets, such as the four approaches and the lamp colours, are enums.
The most important enum is Phase. A phase is a set of approaches that may move at the same time:
public enum Phase { NORTH_SOUTH(Approach.NORTH, Approach.SOUTH), EAST_WEST(Approach.EAST, Approach.WEST), PEDESTRIAN; private final Set<Approach> approaches; Phase(Approach... approaches) { this.approaches = Set.of(approaches); } public boolean serves(Approach approach) { return approaches.contains(approach); }Each vehicle phase holds the two ends of one road. North and south never cross each other, and with no turns allowed, neither do east and west. PEDESTRIAN holds no approach at all.
Do walkers cross with the traffic, or on their own phase?
Alongside the parallel green
Walkers cross beside north-south traffic while it moves, so the junction loses no time. But turning cars would cross the walkers' path, the walk would have to fit inside the green, and both would need rules. Turn arrows are a likely follow-up, and that is when this choice gets costly.
Their own phase, with every vehicle lamp red, and only when someone pressesOur pick
No car moves while anyone walks. The walk is then safe for the same reason a green is: it belongs to a phase that crosses nothing. The cost is a longer cycle whenever someone presses, and no cost when nobody does.
The class diagram
The classes fall into three groups:
- Data: the enums
Approach,Phase,Interval,Lamp,WalkandPreemptResult, and the recordsSignalView,TimingPlan,ClearanceandScheduleEntry. - The core:
SignalController, andDailySchedule, which picks a plan for a time of day. - Outside the code: the timer, the button, the detector, the lamp monitor and the cabinet that switches the lamps. None needs an interface, because the controller never calls them. They call the controller.
Nothing a person or a device does is an error. A press during the walk is ignored, a second road asking for a preemption gets REFUSED_BUSY, and a reset before the signal flashes returns false. A null argument, or a time outside its limits, is a bug in the calling code, and it throws.
Building it
Phases, intervals and the lamps
A phase goes through three intervals. GO shows green to its roads, or WALK in the walk phase. CLEARANCE shows yellow, or flashing DON'T WALK. ALL_RED shows red everywhere, so the junction empties before the next phase. A fourth interval, FLASHING, is the fault state. The lamp colours are worked out from the interval and the phase:
public enum Interval { /** Green for the phase's approaches, or WALK in the pedestrian phase. */ GO, /** Yellow for the phase's approaches, or flashing DON'T WALK. */ CLEARANCE, /** Red everywhere, so the junction empties before the next phase. */ ALL_RED, /** Flashing red everywhere after a fault. */ FLASHING; Lamp lampFor(Phase phase, Approach approach) { return switch (this) { case GO -> phase.serves(approach) ? Lamp.GREEN : Lamp.RED; case CLEARANCE -> phase.serves(approach) ? Lamp.YELLOW : Lamp.RED; case ALL_RED -> Lamp.RED; case FLASHING -> Lamp.FLASHING_RED; }; } Walk walkFor(Phase phase) { if (phase != Phase.PEDESTRIAN) { return Walk.DONT_WALK; } return switch (this) { case GO -> Walk.WALK; case CLEARANCE -> Walk.FLASHING_DONT_WALK; case ALL_RED, FLASHING -> Walk.DONT_WALK; }; }lampFor is the only code that chooses a lamp colour. An approach is green only in GO, and only if the current phase serves it. Here are the fields of the controller:
public final class SignalController { private final Clearance clearance; private TimingPlan plan; private TimingPlan nextPlan; private Phase phase; // null before the first green, and after a reset private Interval interval; private int secondsLeft; private boolean pedestrianWaiting; private Approach preemptedFor; private boolean faultReported;The controller stores one phase, one interval and the seconds left (lines 24 to 26). It stores no colour. North and east cannot both be green, because no value of these three fields describes that. There is only one phase at a time, and no phase holds both roads. The walk is safe the same way: WALK shows only in the walk phase's GO, and that phase serves no approach, so every vehicle lamp is red.
Store each lamp's colour, or work it out?
A colour per approach, set by the controller, with a check before each green
This is easy to picture, and the hardware wants a colour per lamp anyway. But a stored map can hold any mix of colours, including two crossing greens. The check must sit on every path that sets a colour, and a path that forgets it still compiles.
Work every colour out from one phase and one intervalOur pick
Two crossing greens cannot even be written down, so no path can produce them. The cost is that a new kind of signal, such as a turn arrow, needs a new phase and a new lookup rather than one more colour in a map.
One tick at a time
Time moves only when tick() is called. The cabinet's timer calls it once a second, and a test calls it in a loop:
/** One second passes. Returns what the lamps show now. */ public synchronized SignalView tick() { switch (interval) { case GO -> tickGo(); case CLEARANCE -> { if (countDown()) { start(Interval.ALL_RED, clearance.allRedSeconds()); } } case ALL_RED -> { if (countDown()) { startNextPhase(); } } case FLASHING -> { if (!faultReported) { phase = null; start(Interval.ALL_RED, clearance.allRedSeconds()); } } default -> throw new IllegalStateException("no tick rule for " + interval); } return view(); } private void tickGo() { if (secondsLeft > 0) { secondsLeft--; } boolean timeIsUp = secondsLeft == 0 && !holdsGo(); if (timeIsUp || mustEndGo()) { // The only way out of a green or a walk: into its own clearance. start(Interval.CLEARANCE, clearance.secondsAfter(phase)); } }tick() is one switch over the interval. GO counts down in tickGo. When its time is up, or something must end it early, it starts its own CLEARANCE (line 71). That is the only line that leaves GO. CLEARANCE counts down into ALL_RED (line 45), and ALL_RED counts down into startNextPhase (line 50). No line goes from GO to ALL_RED, and none goes from CLEARANCE back to GO. The switch is a statement, which the compiler does not check for missing cases, so the default (line 59) throws for an interval with no rule instead of letting it sit for ever.
A thread that sleeps, or a tick?
A loop that sleeps through each interval
This reads like the real thing. But a test of a 20 second green has to wait 20 seconds or fake the sleep. A button or a preemption then has to wake the sleeping thread, which brings interrupts into the safety code.
A tick() method, called once a second from outsideOur pick
Tests step the signal exactly and check every second. All changes happen in one method under one lock. The Elevator System moves its cars with the same kind of step(). The cost is a resolution of one second. A controller that needs finer steps would change what one tick means, and every limit in Clearance and TimingPlan with it.
Clearance times that no plan can shorten
The yellow, the all-red and the flashing DON'T WALK each have a minimum. They are kept apart from the green times:
public record Clearance(int yellowSeconds, int allRedSeconds, int pedestrianClearanceSeconds) { public static final int MIN_YELLOW_SECONDS = 3; public static final int MIN_ALL_RED_SECONDS = 1; public static final int MIN_PEDESTRIAN_CLEARANCE_SECONDS = 4; private static final int MAX_SECONDS = 60; public Clearance { Seconds.requireBetween("yellow", yellowSeconds, MIN_YELLOW_SECONDS, MAX_SECONDS); Seconds.requireBetween("all-red", allRedSeconds, MIN_ALL_RED_SECONDS, MAX_SECONDS); Seconds.requireBetween("pedestrian clearance", pedestrianClearanceSeconds, MIN_PEDESTRIAN_CLEARANCE_SECONDS, MAX_SECONDS); } /** Yellow for a vehicle phase, flashing DON'T WALK for the pedestrian phase. */ public int secondsAfter(Phase phase) { Objects.requireNonNull(phase, "phase"); return phase == Phase.PEDESTRIAN ? pedestrianClearanceSeconds : yellowSeconds; }The constructor refuses a yellow under 3 seconds, an all-red under 1 second, and under 4 seconds to clear walkers. secondsAfter gives the yellow for a road and the walkers' time for the walk phase (line 27). The controller is given one Clearance when it is built, and no method replaces it.
Where do the yellow and all-red times live?
In each timing plan, next to the green times
There is one record to configure. But a night plan written with a 1 second all-red would be accepted if it passed the plan's own checks. Plans change often, as people tune the traffic, and a mistake there should not touch safety.
In one Clearance, fixed when the controller is builtOur pick
Yellow and all-red depend on the road's width and speed limit, not on the time of day. A plan can make a green longer or shorter, and nothing else. The cost is a second record to pass in.
A plan is only the green times and the walk time:
public record TimingPlan(String name, int northSouthGreenSeconds, int eastWestGreenSeconds, int walkSeconds) { public static final int MIN_GREEN_SECONDS = 5; public static final int MAX_GREEN_SECONDS = 180; public static final int MIN_WALK_SECONDS = 5; public static final int MAX_WALK_SECONDS = 60; public TimingPlan { Objects.requireNonNull(name, "name"); if (name.isBlank()) { throw new IllegalArgumentException("a plan needs a name"); } Seconds.requireBetween("north-south green", northSouthGreenSeconds, MIN_GREEN_SECONDS, MAX_GREEN_SECONDS); Seconds.requireBetween("east-west green", eastWestGreenSeconds, MIN_GREEN_SECONDS, MAX_GREEN_SECONDS); Seconds.requireBetween("walk", walkSeconds, MIN_WALK_SECONDS, MAX_WALK_SECONDS); } public int goSeconds(Phase phase) { Objects.requireNonNull(phase, "phase"); return switch (phase) { case NORTH_SOUTH -> northSouthGreenSeconds; case EAST_WEST -> eastWestGreenSeconds; case PEDESTRIAN -> walkSeconds; }; }A green can be 5 to 180 seconds, and a walk 5 to 60 (lines 19 to 21). Every limit is checked in the constructor, so a bad plan is refused when it is written, not when the evening rush begins.
A new plan waits for the next cycle
DailySchedule says which plan should run at a time of day. planAt returns the last entry that starts at or before that time:
public TimingPlan planAt(LocalTime time) { Objects.requireNonNull(time, "time"); TimingPlan plan = entries.get(0).plan(); for (ScheduleEntry entry : entries) { if (entry.start().isAfter(time)) { break; } plan = entry.plan(); } return plan; }The constructor makes sure the first entry starts at midnight, so every time of day has a plan. The cabinet's timer asks once a minute and passes the answer to usePlan:
/** Takes effect when the next cycle starts. The latest request wins. */ public synchronized void usePlan(TimingPlan requested) { nextPlan = Objects.requireNonNull(requested, "requested"); }usePlan only records the plan in nextPlan. The swap happens when the next phase starts:
private void startNextPhase() { if (faultReported) { preemptedFor = null; start(Interval.FLASHING, 0); return; } Phase next = preemptedFor != null ? Phase.serving(preemptedFor) : nextInOrder(); // A plan changes only as north-south turns green, where a cycle starts. if (next == Phase.NORTH_SOUTH && nextPlan != null) { plan = nextPlan; nextPlan = null; } if (next == Phase.PEDESTRIAN) { pedestrianWaiting = false; } phase = next; start(Interval.GO, plan.goSeconds(next)); }A new plan takes over only as north-south turns green (lines 99 to 102), and that is where a cycle starts. The green that is running keeps its time, because secondsLeft was set when it started. East-west, later in the same cycle, still gets the old plan's time. Two requests in one cycle leave the later one in nextPlan, and asking for the plan already running replaces a pending one with no change. So asking every minute is harmless.
When does a new plan take effect?
At once, cutting or stretching the green that is running
The evening plan starts on the dot. But a green that has run 25 seconds would end at once under a 20 second plan, and the cycle in progress would have a length that matches no plan.
At the start of the next phase
Nothing running is cut. But one cycle can then mix two plans, with north-south on the day time and east-west on the evening time. A later green wave, which counts on every cycle having a known length, would drift.
At the start of the next cycleOur pick
Every cycle runs on one plan from start to end. The cost is a wait of up to one cycle for the new plan, under a minute and a half with these plans. A preemption that holds a green delays it further.
Outside events leave a note
The button, the detector, the monitor and the schedule never touch the lamps. Each one changes a request field and returns:
/** A press while WALK is showing does nothing: the walker can go now. */ public synchronized void pressPedestrianButton() { if (interval == Interval.GO && phase == Phase.PEDESTRIAN) { return; } pedestrianWaiting = true; } public synchronized PreemptResult preempt(Approach approach) { Objects.requireNonNull(approach, "approach"); // A reset takes effect at the next tick, so the signal can still be flashing here. if (faultReported || interval == Interval.FLASHING) { return PreemptResult.REFUSED_FAULT; } if (preemptedFor != null && preemptedFor != approach) { return PreemptResult.REFUSED_BUSY; } preemptedFor = approach; return PreemptResult.ACCEPTED; }None of these methods changes phase, interval or secondsLeft, so none of them can change a lamp. Only the next tick() can, through the path in the figure above. Repeated calls are harmless. Ten presses set pedestrianWaiting ten times, and startNextPhase clears it when the walk begins (line 104). A press while WALK shows is ignored, because the walker can cross now. A press during flashing DON'T WALK is kept for the next cycle.
Do outside events change the lamps at once, or at the next tick?
At once: preempt starts the yellow inside the call
The ambulance gains up to a second. But every event method then needs its own copy of the safety rules. A reset that arrived between two ticks would also start its all-red part of the way through a second, so the all-red would show for less than its full time.
At the next tick: an event records a request, and tick() acts on itOur pick
Only tick() moves the signal, so the safety argument covers one method. Every interval begins on a tick or at start-up, and runs for whole seconds. The cost is up to one second of delay for every event.
An emergency vehicle
preempt records one approach in preemptedFor. A request from that same approach is accepted again, which makes a detector's retry safe. A request from any other approach gets REFUSED_BUSY until the first ends, and the detector asks again later. On each tick, two small methods decide what the request means for the green that is running:
private boolean mustEndGo() { if (faultReported) { return true; } return preemptedFor != null && !phase.serves(preemptedFor); } private boolean holdsGo() { return preemptedFor != null && phase.serves(preemptedFor); }mustEndGo ends any green that does not serve the vehicle's approach, including a walk. It ends it the only way GO can end: through its full clearance and the all-red. Then startNextPhase picks the vehicle's phase (line 97), and holdsGo keeps that green past its time until the detector calls endPreemption. A yellow already running is never cut, because a preemption can only end GO. A road that is yellow when the vehicle arrives goes red, then green again, and never straight back from yellow to green.
An emergency vehicle is coming. When does the current green end?
When its time is up, as normal
Nothing is cut short. But the ambulance can wait a whole green, which can be three minutes on a long plan.
At once, straight to red
This is the fastest. But a driver who had a green sees red with no warning, which breaks the first rule we set.
At the next tick, through the full yellow and all-redOur pick
No driver or walker loses their clearance, and the wait is short: in the demo, the ambulance's road turns green 6 seconds after it asks. The cost is that a green can be very short, even one second, when a vehicle arrives just after it started. Preemption can also starve the rest of the junction. A detector that never calls endPreemption holds its green for ever. A detector that keeps asking for north-south whenever east-west turns green leaves east-west with one-second greens and the walkers with none. A walk cut after a second is not owed again, because pedestrianWaiting was cleared when it began. The follow-ups below give the fixes.
A fault
The lamp monitor calls reportFault, which sets faultReported. mustEndGo checks it first (lines 81 to 83), so the next tick ends any green, even one held for an ambulance. When the all-red finishes, startNextPhase sees the fault, drops any preemption and moves to FLASHING (lines 92 to 96). While the fault stands, and while the signal is still flashing after a reset, preempt answers REFUSED_FAULT (line 133). Without that second test, a preemption accepted between a reset and its tick would survive a new fault. After the next reset its road would be held green until that detector ends it, which may be long after the vehicle has gone. The detector is not told. It must call preempt again after the reset, and a retry from the same approach is safe.
public synchronized void reportFault() { faultReported = true; } /** A technician's reset. It works only once the signal is flashing. */ public synchronized boolean reset() { if (interval != Interval.FLASHING) { return false; } faultReported = false; return true; }reset works only once the signal is flashing, and it only clears the fault. The next tick sees that and starts an all-red with no phase, so the cycle starts again at north-south, unless a preemption accepted during that all-red picks its own road. A fault reported again before that tick keeps the signal flashing.
A fault. Flash at once, or through the clearance?
Flash at once
The signal stops trusting itself immediately. But a driver who had a green sees flashing red with no warning, at speed.
Through the clearance, then flashOur pick
The monitor reports while the lamps still work, so drivers get the yellow and all-red as usual. A fault that means the controller cannot be trusted at all, such as two greens seen on the wires, needs hardware outside this code that cuts to flashing by itself. The cost is a few seconds of normal clearance before the flash.
The demo's three minutes show all three outside events reaching the lamps:
Many callers, one lock
The timer, the button, the detector, the monitor and the schedule call from their own threads. Every public method of SignalController is synchronized, so the controller's own monitor is the one lock. Each method holds it for a few field reads and writes. No method calls outside code, so the lock is never held while something slow runs.
Without the lock, preempt breaks first. It reads preemptedFor, then sets it. Two detectors can both read null and both be told ACCEPTED:
The project includes demo/RaceCheck.java. Four detector threads, one per approach, wait for a round to open and then call preempt at the same moment. It runs 2,000 rounds, each with a new controller:
2000 rounds, four detectors at once in each rounds with exactly one ACCEPTED: 2000 rounds with more than one ACCEPTED: 0
Every round told exactly one detector ACCEPTED. We also ran it in a scratch copy with synchronized taken off preempt. In each of six runs, more than half the rounds told two or more detectors ACCEPTED. The exact numbers change from run to run and from machine to machine.
Where does the lock go?
No lock: volatile flags, and an atomic for the preemption
Each flag on its own is safe. But tick() reads several fields and then changes plan, nextPlan and pedestrianWaiting. A plan that arrives between the read and the clear of nextPlan would be lost, and each such gap would need its own fix.
One lock: every public method is synchronizedOur pick
Each method runs whole, so tick() sees the requests as they stood and changes them in one step. Every method is a few lines with no outside call, and the busiest caller ticks once a second, so no caller waits long. The cost is that any code holding the controller could lock it too. A private lock object would close that gap.
The final design
SignalController is the core. It holds one phase, one interval, the seconds left and the requests waiting for the next tick, all under its own lock. It reads green times from a TimingPlan and clearance times from a fixed Clearance, and looks up every lamp through Interval. It calls no outside code: the timer and the devices call it.
| S.No. | The question | What we chose | Why |
|---|---|---|---|
| 1 | Should each traffic light be its own object? | No. One SignalController holds the only state, and a light shows what it is told | Lights that change on their own can disagree |
| 2 | Do walkers cross with the traffic, or on their own phase? | Their own phase, with every vehicle lamp red, and only when someone presses | The walk crosses nothing, like a green |
| 3 | Store each lamp's colour, or work it out? | Work every colour out from one phase and one interval | Two crossing greens cannot be written down |
| 4 | A thread that sleeps, or a tick? | A tick() method, called once a second from outside | Tests step the signal exactly |
| 5 | Where do the yellow and all-red times live? | In one Clearance, fixed when the controller is built | A plan cannot shorten a clearance |
| 6 | When does a new plan take effect? | At the start of the next cycle | Every cycle runs on one plan |
| 7 | Do outside events change the lamps at once, or at the next tick? | At the next tick: an event records a request, and tick() acts on it | Only one method moves the signal |
| 8 | An emergency vehicle is coming. When does the current green end? | At the next tick, through the full yellow and all-red | Fast, and no clearance is cut |
| 9 | A fault. Flash at once, or through the clearance? | Through the clearance, then flash | Drivers still get their yellow |
| 10 | Where does the lock go? | One lock: every public method is synchronized | tick() sees and changes the requests in one step |
Here is the ambulance from the demo, end to end:
- The east detector calls
preempt(EAST). It takes the controller's lock, findspreemptedForempty, recordsEASTand returnsACCEPTED. No lamp has changed. - The timer calls
tick(), which takes the same lock.tickGoasksmustEndGo, which sees that north-south does not serveEAST, so it starts north-south's CLEARANCE withsecondsAfter. - Four ticks later CLEARANCE becomes ALL_RED, and two after that
startNextPhasepicksPhase.serving(EAST)and starts east-west's GO. - When east-west's time runs out,
holdsGokeeps it green. The detector callsendPreemption(EAST), and the nexttickGostarts the yellow. - Every
tick()returns aSignalViewbuilt bylampForandwalkFor, and the cabinet switches the lamps from it after the lock is released.
The complete code
Here is the whole project. Click any class name to jump to its file, or use Find a file to search. Badges in the tree show what each file is: a class, an enum or a record.
package signal; import java.util.EnumMap;import java.util.Map;import java.util.Objects; import road.Approach;import road.Phase;import timing.Clearance;import timing.TimingPlan; /** * The controller for one junction. It holds the only copy of the signal's * state: one phase, one interval and the seconds left in it. Every lamp is * worked out from those three. Time moves only in tick(). The other methods * record a request, and the next tick acts on it. Every public method is * synchronized, so the controller's own monitor is the one lock. */public final class SignalController { private final Clearance clearance; private TimingPlan plan; private TimingPlan nextPlan; private Phase phase; // null before the first green, and after a reset private Interval interval; private int secondsLeft; private boolean pedestrianWaiting; private Approach preemptedFor; private boolean faultReported; public SignalController(Clearance clearance, TimingPlan plan) { this.clearance = Objects.requireNonNull(clearance, "clearance"); this.plan = Objects.requireNonNull(plan, "plan"); this.interval = Interval.ALL_RED; this.secondsLeft = clearance.allRedSeconds(); } /** One second passes. Returns what the lamps show now. */ public synchronized SignalView tick() { switch (interval) { case GO -> tickGo(); case CLEARANCE -> { if (countDown()) { start(Interval.ALL_RED, clearance.allRedSeconds()); } } case ALL_RED -> { if (countDown()) { startNextPhase(); } } case FLASHING -> { if (!faultReported) { phase = null; start(Interval.ALL_RED, clearance.allRedSeconds()); } } default -> throw new IllegalStateException("no tick rule for " + interval); } return view(); } private void tickGo() { if (secondsLeft > 0) { secondsLeft--; } boolean timeIsUp = secondsLeft == 0 && !holdsGo(); if (timeIsUp || mustEndGo()) { // The only way out of a green or a walk: into its own clearance. start(Interval.CLEARANCE, clearance.secondsAfter(phase)); } } private boolean countDown() { secondsLeft--; return secondsLeft == 0; } private boolean mustEndGo() { if (faultReported) { return true; } return preemptedFor != null && !phase.serves(preemptedFor); } private boolean holdsGo() { return preemptedFor != null && phase.serves(preemptedFor); } private void startNextPhase() { if (faultReported) { preemptedFor = null; start(Interval.FLASHING, 0); return; } Phase next = preemptedFor != null ? Phase.serving(preemptedFor) : nextInOrder(); // A plan changes only as north-south turns green, where a cycle starts. if (next == Phase.NORTH_SOUTH && nextPlan != null) { plan = nextPlan; nextPlan = null; } if (next == Phase.PEDESTRIAN) { pedestrianWaiting = false; } phase = next; start(Interval.GO, plan.goSeconds(next)); } private Phase nextInOrder() { if (phase == null) { return Phase.NORTH_SOUTH; } return phase.next(pedestrianWaiting); } private void start(Interval next, int seconds) { interval = next; secondsLeft = seconds; } /** A press while WALK is showing does nothing: the walker can go now. */ public synchronized void pressPedestrianButton() { if (interval == Interval.GO && phase == Phase.PEDESTRIAN) { return; } pedestrianWaiting = true; } public synchronized PreemptResult preempt(Approach approach) { Objects.requireNonNull(approach, "approach"); // A reset takes effect at the next tick, so the signal can still be flashing here. if (faultReported || interval == Interval.FLASHING) { return PreemptResult.REFUSED_FAULT; } if (preemptedFor != null && preemptedFor != approach) { return PreemptResult.REFUSED_BUSY; } preemptedFor = approach; return PreemptResult.ACCEPTED; } /** Ends the preemption only if this approach holds it. */ public synchronized boolean endPreemption(Approach approach) { Objects.requireNonNull(approach, "approach"); if (preemptedFor != approach) { return false; } preemptedFor = null; return true; } /** Takes effect when the next cycle starts. The latest request wins. */ public synchronized void usePlan(TimingPlan requested) { nextPlan = Objects.requireNonNull(requested, "requested"); } public synchronized void reportFault() { faultReported = true; } /** A technician's reset. It works only once the signal is flashing. */ public synchronized boolean reset() { if (interval != Interval.FLASHING) { return false; } faultReported = false; return true; } public synchronized SignalView view() { Map<Approach, Lamp> lamps = new EnumMap<>(Approach.class); for (Approach approach : Approach.values()) { lamps.put(approach, interval.lampFor(phase, approach)); } return new SignalView(plan.name(), interval, secondsLeft, lamps, interval.walkFor(phase), pedestrianWaiting); }}demo/Main.java runs three minutes at one junction, one tick per second. A walker presses ten times, the schedule asks for the evening plan in the middle of a cycle, an ambulance and a fire engine ask for a green, and the lamp monitor reports a fault:
16:58:50 RED NORTH SOUTH EAST WEST DONT_WALK (day, 2s) 16:58:52 GREEN NORTH SOUTH RED EAST WEST DONT_WALK (day, 20s) 16:59:00 schedule asks for the day plan 16:59:12 YELLOW NORTH SOUTH RED EAST WEST DONT_WALK (day, 4s) 16:59:16 RED NORTH SOUTH EAST WEST DONT_WALK (day, 2s) 16:59:18 GREEN EAST WEST RED NORTH SOUTH DONT_WALK (day, 15s) 16:59:20 button pressed 10 times, waiting: true 16:59:33 YELLOW EAST WEST RED NORTH SOUTH DONT_WALK (day, 4s) 16:59:37 RED NORTH SOUTH EAST WEST DONT_WALK (day, 2s) 16:59:39 RED NORTH SOUTH EAST WEST WALK (day, 8s) 16:59:47 RED NORTH SOUTH EAST WEST FLASHING_DONT_WALK (day, 10s) 16:59:57 RED NORTH SOUTH EAST WEST DONT_WALK (day, 2s) 16:59:59 GREEN NORTH SOUTH RED EAST WEST DONT_WALK (day, 20s) 17:00:00 schedule asks for the evening plan 17:00:19 YELLOW NORTH SOUTH RED EAST WEST DONT_WALK (day, 4s) 17:00:23 RED NORTH SOUTH EAST WEST DONT_WALK (day, 2s) 17:00:25 GREEN EAST WEST RED NORTH SOUTH DONT_WALK (day, 15s) 17:00:40 YELLOW EAST WEST RED NORTH SOUTH DONT_WALK (day, 4s) 17:00:44 RED NORTH SOUTH EAST WEST DONT_WALK (day, 2s) 17:00:46 GREEN NORTH SOUTH RED EAST WEST DONT_WALK (evening, 30s) 17:00:55 ambulance from EAST: ACCEPTED 17:00:55 YELLOW NORTH SOUTH RED EAST WEST DONT_WALK (evening, 4s) 17:00:58 fire engine from NORTH: REFUSED_BUSY 17:00:59 RED NORTH SOUTH EAST WEST DONT_WALK (evening, 2s) 17:01:00 schedule asks for the evening plan 17:01:01 GREEN EAST WEST RED NORTH SOUTH DONT_WALK (evening, 10s) 17:01:03 ambulance from EAST again: ACCEPTED 17:01:20 ambulance has passed: true 17:01:20 YELLOW EAST WEST RED NORTH SOUTH DONT_WALK (evening, 4s) 17:01:24 RED NORTH SOUTH EAST WEST DONT_WALK (evening, 2s) 17:01:26 GREEN NORTH SOUTH RED EAST WEST DONT_WALK (evening, 30s) 17:01:35 lamp monitor reports a fault 17:01:35 YELLOW NORTH SOUTH RED EAST WEST DONT_WALK (evening, 4s) 17:01:39 RED NORTH SOUTH EAST WEST DONT_WALK (evening, 2s) 17:01:41 FLASHING_RED NORTH SOUTH EAST WEST DONT_WALK (evening, 0s) 17:01:50 ambulance from WEST: REFUSED_FAULT 17:01:55 technician resets: true 17:01:55 RED NORTH SOUTH EAST WEST DONT_WALK (evening, 2s) 17:01:57 GREEN NORTH SOUTH RED EAST WEST DONT_WALK (evening, 30s) 17:02:00 schedule asks for the evening plan
Notice three things in the output. Ten presses at 16:59:20 bring one walk at 16:59:39: 8 seconds of WALK, then 10 of flashing DON'T WALK, with every vehicle lamp red. The evening plan asked for at 17:00:00 waits: the cycle in progress keeps 20 and 15 seconds, and the 30 second green arrives at 17:00:46. And the ambulance at 17:00:55 gets a yellow in the same second, but its green only at 17:01:01, after the full yellow and all-red, while the fire engine is refused.
Follow-up questions
After the core design, the interviewer adds a requirement to see how the design bends. For each one, say which class changes and which do not.
| The interviewer asks | What changes | What does not |
|---|---|---|
| "Link the junctions on a road into a green wave." | Each controller gets a cycle length and an offset, and starts each cycle on a shared clock. Plans already change only at a cycle start, which this needs. | The phases, the intervals and the clearance. |
| "Stretch the green when traffic is heavy." | Sensors count cars, and a rule turns counts into green times. The rule sits behind an interface that startNextPhase asks. This is where a Strategy fits. | The interval sequence and the lamp lookup. |
| "Add left-turn arrows." | New phases such as north-left, and a conflict table that checks each phase when it is built, since two fixed roads are no longer enough. Lamp gains arrow colours, and lampFor looks up movements, not approaches. | tick() and the order GO, CLEARANCE, ALL_RED. |
| "Serve two emergency vehicles at once." | A queue in place of preemptedFor, served in turn, each through the clearance. PreemptResult gains a QUEUED answer. | The way a green ends. |
| "Stop a preemption from starving the other road and the walk." | A maximum hold time in holdsGo, after which the held green ends anyway. A walk cut short sets pedestrianWaiting again, so it is still owed. | The clearance path and the one-at-a-time rule. |
| "Keep a minimum green before a preemption cuts it." | The controller remembers how long the green has run, and mustEndGo waits for the minimum. | Everything else. |
| "Let walkers cross beside the traffic." | The walk becomes part of each vehicle phase's GO, and walkFor changes. Turning cars must then be kept out of the crosswalk. | The plan swap, preemption and faults. |
| "Flash yellow on the main road at night." | A night mode chosen by the plan, with its own lookup in lampFor, entered through the clearance like a fault. | Fault handling and the day cycle. |
| "Survive a power cut." | Little to save. A restart begins in all-red, as the constructor does, with the plan from planAt. A button press from before the cut is lost. | The design. |
| "Show walkers a countdown." | A display reads secondsLeft from the SignalView during flashing DON'T WALK. | The controller. |
Most rows change one method or add a small class beside the core. Two are bigger: turn arrows replace the two fixed roads with phases checked against a conflict table, and a green wave makes cycle timing a shared concern between junctions.
What the interviewer looks for
Mid-level
A mid-level candidate shows a controller that cycles the phases with a yellow between them, enums for the colours, and times from a plan. They make sure the two roads are never green together, even if they do it with a check rather than by design.
Senior
A senior candidate shows everything above and makes crossing greens impossible to store. They add the all-red, keep clearance times out of the plans, and swap plans only at a cycle start. They drive time with a tick so tests are exact, and they send an ambulance through the full clearance.
Staff+
A staff candidate leads with the safety argument and keeps every lamp change in one method. They let events only leave a note for the next tick, and say why that keeps the argument small. They explain what software cannot promise, such as a stuck relay, and what hardware must do about it. They also say what a green wave would need from plans and cycle starts.
Common mistakes
- A light object per approach, each with its own timer. The lights can drift apart, and nothing stops two crossing greens.
- Storing a colour per lamp and checking before each green. The check has to be on every path, and one missed path is a crash at the junction.
- Going from green straight to red, or skipping the all-red. A car that entered on yellow has no time to clear the junction.
- Letting a plan carry the yellow time. A plan written for the night can then shorten a safety interval.
- Changing the plan at once. The green that is running is cut or stretched, and one cycle ends up with no plan's length.
- Cutting the yellow for an ambulance. The emergency is real, and so is the car already in the junction.
- Sleeping threads for timing. Tests become slow and flaky, and events have to interrupt the sleeper.
Summary
- Keep one phase and one interval, and work every lamp out from them, so two crossing greens cannot be stored.
- Leave GO only through its own clearance and then the all-red, in one method.
- Put yellow and all-red in a fixed
Clearance, and let plans change only green and walk times. - Swap plans only as a cycle starts, so every cycle runs on one plan.
- Let the button, the detector, the monitor and the schedule only leave a request, and let the next tick act on it.
- An ambulance ends a green through the full clearance, and a fault does the same before the flashing.
- Guard everything with one lock, and drive time with
tick()so every second can be tested.