Machine Coding Problem

Traffic Signal Controller

macoAllinfrastructurestate-patterntimerssafety-invariants

Requirements & System Scope

Functional Scope (In-Scope)

The controller runs one four-way intersection. Its job is to hand out right of way in turns, and to make it impossible for two crossing streams of traffic to be released together.

  • Signal Heads and Axes: One SignalHead per approach (north, south, east, west) showing red, yellow, green or flashing red. North and south share an axis, east and west share an axis, and the two axes conflict.
  • State-Pattern Phase Machine: Each phase is an object that knows which lights it shows, how long it lasts and which phase comes next.
  • Mandatory Clearance: Every change of right of way passes through a 4 second yellow and a 2 second all-red interval. Neither is ever shortened.
  • One Safety Invariant: Two conflicting approaches are never green or yellow together, and the walk lamp is never lit while any vehicle approach is not red. One method enforces it for every state.
  • Pedestrian Requests: A button press is queued and served at the next safe phase boundary by an exclusive walk phase. Repeated presses collapse into one request.
  • Emergency Preemption: An emergency vehicle gets right of way by passing through yellow and all-red first, never by jumping straight to a conflicting green.
  • Fail-Safe Mode: A reported fault, or any attempt to show an unsafe picture, drops every head to flashing red until a technician resets the controller.
  • Pluggable Timing: A fixed-time plan and a simplified vehicle-actuated plan sit behind one interface.
  • Thread-Safe Entry Points: A timer, detectors, pedestrian buttons and the preemption receiver all call in from different threads.

Explicit Boundaries (Out-of-Scope)

The design stays small enough to finish in an interview, so several real controller features are deliberately left out.

  • No Protected Left Turns: Each phase serves the through and turning movements of one axis together. Adding left-turn phases means more PhaseState subclasses and a richer conflict table, not a different design.
  • No Real Hardware: Lamp drivers, load switches and the independent hardware conflict monitor are represented by SignalHead objects and the software check in Intersection.
  • No Network of Intersections: Green waves, remote monitoring and heartbeats are extensions, not part of the blueprint.
  • No Pedestrian Countdown: The 12 second walk phase covers the walk and the pedestrian clearance as one interval with the walk lamp lit throughout.
  • No Gap-Out Detectors: The actuated plan sizes a green once when it starts. A real controller re-reads detectors during the green.

Class Diagram & Entity Relationships

How the Classes Fit Together

The controller owns the lamps, the queue of pending requests and a single current phase. Each phase is a small object that says which lights it wants, how long it lasts and what follows it. The lamps accept a new picture only through one checked method, which is where the safety rule lives. Every field and method in the diagram mirrors the Java blueprint.

Loading...

Reading the Diagram

  • State spine: SignalController holds one PhaseState and calls next(ctx) when the phase expires. It never asks which phase it is in, so a new phase is a new subclass and nothing else changes.
  • Single enforcement point: Intersection.show() is the only code that writes to the SignalHead objects, and it calls violation() first. States describe what they want to show, and the intersection decides whether that picture is allowed.
  • Requests as data: PhaseContext holds the queued emergency axes, the pedestrian flag and the detector counts. Callers only add to it, and phases take from it at their own boundary.
  • Seams for testing and growth: Clock lets the driver step time by hand, TimingPlan swaps the green policy, and SignalListener receives immutable Snapshot values.

Design Patterns & SOLID Principles

Patterns the Blueprint Uses

Each pattern below maps to a class in the code, and none of them is decoration. They are the reason a new phase, a new timing policy or a new monitor can be added without editing the safety code.

  • State Pattern (Phase Machine):PhaseState is the abstract state, and GreenState, YellowState, AllRedState, PedestrianState, EmergencyState and FlashingRedState are the concrete states. Each one answers lights(), durationMs() and next(ctx), and a state may override onEmergency(axis, ctx) to react to preemption. SignalController stores one state and delegates to it, so the only code that knows the order of the cycle is the states themselves.
  • Strategy Pattern (Timing Plan):TimingPlan has one method, greenMs(axis, waiting), with FixedTimePlan and ActuatedPlan as interchangeable policies. PhaseContext.green() calls the plan whenever a green is created, so changing the policy never touches a clearance interval.
  • Observer Pattern (Phase Notifications):SignalController keeps a list of SignalListener objects and calls phaseChanged(atMs, snapshot) after every phase change. ConsoleLogger is the demo listener, and a monitoring uplink or a pedestrian display would be others.
  • Dependency Inversion Principle (DIP) (Clock): The controller depends on the Clock interface rather than the system time. The driver passes a ManualClock and advances it one second at a time, which makes every run reproducible and removes the need to sleep.
  • Interface Segregation Principle (ISP) (Narrow Contracts): Each collaborator sees only the one method it needs. Clock exposes only nowMs, TimingPlan exposes only greenMs, and SignalListener receives only phaseChanged with an immutable Snapshot instead of the mutable Intersection. A monitoring uplink therefore cannot change a lamp, and a new timing plan never has to implement anything unrelated to timing.
  • Single Responsibility (Safety Rule):Intersection alone knows which approaches conflict and which pictures are legal. States do not validate themselves, and the controller does not know the rule, so a mistake in a phase can only produce a rejected picture and never a conflicting green.

Algorithm: Fixed-Time Cycle and Vehicle-Actuated Timing

Baseline: the fixed-time cycle

The reference plan repeats one loop forever. One axis gets its green, then a 4 second yellow, then a 2 second all-red clearance, and then the other axis takes its turn. With a 30 second green per axis the cycle length is 2 ร— (30 + 4 + 2) = 72 seconds. Twelve of those seconds (2 ร— (4 + 2), about 16.7 percent) are lost to clearance, and each axis is green for 30 / 72, about 41.7 percent of the time.

  1. Show the green for one axis and hold it for its green time (30 seconds in the demo).
  2. Show yellow on that axis for 4 seconds so drivers can stop or clear the box.
  3. Show red on every approach for 2 seconds so the last vehicle clears before the crossing traffic starts.
  4. Repeat for the other axis.

An approach waits at most one cycle minus its own green, which is 72 minus 30, or 42 seconds. A pedestrian request adds a 12 second walk phase to the cycle that serves it, so that cycle is 84 seconds. In the demo run a button is pressed at second 8, the north-south green still has 24 seconds left, and the walk starts at second 38 after the 4 second yellow and the 2 second clearance. The worst-case wait for a pedestrian is about 36 seconds, a full green plus the yellow and the clearance.

The weakness is wasted green. At three in the morning a lone car on the north approach can still wait up to 42 seconds on red while the east and west greens run for nobody.

Optimization: vehicle actuation (the aha moment)

An actuated controller replaces the single green number with three. A minimum green gives a stopped driver time to start moving, an extension keeps the green alive while detectors still see vehicles arriving, and a maximum green caps the phase so the cross street cannot be starved. A phase with no demand is shortened to its minimum or skipped. The aha is that yellow and all-red stay constants, so only the green length varies. The safety argument does not depend on the timing plan at all, which is why TimingPlan can be swapped freely.

The blueprint's ActuatedPlan is the simplified form. When a green starts it reads the larger queue of the axis's two approaches, because both approaches discharge together, and it returns min(max, min + perVehicle ร— queue). With a 10 second minimum, 2 seconds per vehicle and a 40 second maximum, six vehicles on the east approach and four on the west give a 22 second green while the empty north-south axis gets only its 10 second minimum. The cycle drops from 72 seconds to (10 + 6) + (22 + 6) = 44 seconds, and fifteen or more waiting vehicles reach the 40 second cap. It does not re-read detectors during the green and it does not skip an empty axis outright, because a real skip decision has to be made before the yellow starts, otherwise the clearance is paid for no benefit.

Trade-offs

  • Detector faults: A detector stuck on pins the green at its maximum every cycle, and one stuck off reduces its approach to the minimum green. Production controllers detect both and fall back to the fixed plan.
  • Starvation: The maximum green bounds the wait. With the blueprint numbers a side street waits no more than 46 seconds (a 40 second maximum green plus clearance), plus any pedestrian or emergency phase in between.
  • Coordination: Green waves along a road assume neighbouring signals share one fixed cycle. Free-running actuation breaks that assumption unless it is anchored to a background cycle.
  • Testing cost: A fixed plan is reproducible from the clock alone, while an actuated plan needs simulated detector traffic to exercise it.

Complexity

Every tick is constant time. The safety check compares the 6 pairs of 4 approaches and scans 4 lights for the walk rule, and a request is one flag write, one deque append bounded by the two axes, or one counter increment.

Core Execution Workflows

1. Normal Tick and Phase Change

Every phase change in the system, including the ones caused by requests, goes through this one path.

  1. The timer calls tick(), which takes the controller lock. The driver advances the manual clock by one second and then calls it.
  2. If an emergency request is queued, the current state is asked onEmergency(axis, ctx). Most states answer with themselves (see flow 3).
  3. If the clock has reached phaseEndsAtMs, the controller asks the current state for next(ctx). A green returns the yellow for its axis, a yellow returns the all-red, and the all-red picks an emergency, then a pedestrian walk, then the green of the other axis.
  4. enter(next) hands the new picture to Intersection.show(lights, walk). violation() runs first and, when it passes, the four heads and the walk lamp are written.
  5. The controller stores the new state, sets phaseEndsAtMs to the current time plus the state's duration, builds a Snapshot and calls phaseChanged on every listener.
  6. Failure path: when violation() reports a conflict, show() throws before any head changes. enter() catches it, swaps the candidate for FlashingRedState with a โ€œconflict monitorโ€ reason, and applies that instead.
  7. Failure path: a late tick cannot shorten a phase, because the end time is measured from the moment the phase was entered. It can only stretch a phase by the lateness.

2. Pedestrian Request

A button press is data, not an action. It waits in the context until the controller reaches a boundary where every vehicle approach is already red.

  1. A button thread calls requestPedestrian(). The method takes the lock, sets pedestrianWaiting and returns. No lamp changes.
  2. Further presses while the flag is set change nothing, so three simultaneous presses become one request.
  3. When AllRedState.next runs, it checks for an emergency first. Otherwise takePedestrian() returns true, clears the flag, and the state returns PedestrianState for the axis that was due next.
  4. PedestrianState shows every vehicle approach red with the walk lamp on for 12 seconds. Its next returns the green for the axis that was due, so the walk delays the cycle by 12 seconds and does not reorder it.
  5. In the demo the press at second 8 is served at second 38, and the east-west green starts at second 50 instead of second 38.
  6. Failure path: a press during the walk sets the flag again and is served at the next all-red. A press during a fault stays queued and is served after the reset. An emergency queued at the same boundary goes first and leaves the pedestrian flag untouched.

3. Emergency Preemption

The request is queued by the caller, and the state machine decides how to react at its next tick. The reaction depends on what the lamps are showing right now.

  1. A preemption receiver calls requestEmergency(from). The controller records the axis of that approach at the end of a queue unless it is already there, so ambulances from north and south become one request.
  2. On the next tick the current state's onEmergency decides:
    1. A green on the same axis returns EmergencyState for that axis and removes the request. The lamps do not change and the green is held for 10 seconds from now.
    2. A green on the conflicting axis returns the yellow for its own axis, so the green ends at once even if it had time left. The request stays queued.
    3. A yellow, an all-red, a pedestrian walk or an emergency hold on the other axis ignores the request and finishes its interval.
  3. When AllRedState.next or PedestrianState.next runs, a queued emergency is taken before anything else and the state returns EmergencyState for that axis.
  4. After the 10 second hold, EmergencyState.next returns the yellow for that axis, then the all-red, and the normal cycle resumes with the other axis.
  5. In the demo the ambulances report at second 60 while east-west is green. The yellow starts at 61, the all-red at 65, the north-south emergency green at 67, its yellow at 77, its all-red at 81 and the east-west green at 83. The ambulance waited 7 seconds: one tick, a 4 second yellow and a 2 second clearance.
  6. Failure path: the slowest case is an emergency hold on the other axis, which costs 10 + 4 + 2 = 16 seconds. A fault during preemption goes to flashing red like any other fault.

4. Fault and Recovery

A fault is the one request that is applied immediately, because flashing red gives nobody right of way and so cannot conflict with whatever was showing.

  1. A monitoring thread calls reportFault(reason). Under the lock the controller enters FlashingRedState. All four heads flash red, the walk lamp goes off, and the phase lasts forever, so later ticks change nothing.
  2. Pedestrian, emergency and detector requests keep queueing while the fault lasts.
  3. A technician calls reset(). It does nothing unless the controller is flashing, and then it enters AllRedState as if the east-west axis had just cleared, so north-south is next after 2 seconds of all-red unless a queued emergency or pedestrian goes first.
  4. In the demo the fault at second 100 flashes every head, the reset at second 105 shows all-red, and north-south turns green at second 107.

5. Sizing a Green from Detector Counts

With the actuated plan the length of a green is decided when it starts, from the queue the detectors saw.

  1. A detector thread calls vehicleDetected(from), which increments a per-approach counter in the context under the lock.
  2. When PhaseContext.green(axis) runs, it takes the larger of the two counters on that axis, resets both, and asks the TimingPlan for a green length.
  3. The blueprint assumes the green it sizes serves the queue it saw. Vehicles that arrive during the green are counted for the next one.

Concurrency & Thread Safety Strategy

Shared State and Who Touches It

Five kinds of caller share one controller. The timer thread calls tick(), detector threads call vehicleDetected, button handlers call requestPedestrian, a preemption receiver calls requestEmergency, and a monitoring thread calls reportFault, reset and snapshot. They all reach the same mutable state: the current state and phaseEndsAtMs, the four SignalHead objects and the walk lamp inside Intersection, and the pending requests and detector counts inside PhaseContext.

The Races This Prevents

  • Lost pedestrian press: takePedestrian() reads the flag and then clears it. If the timer thread reads false, a button thread sets the flag, and the timer thread then writes false, the press is erased. The pedestrian waits a whole extra cycle or gives up and crosses against the lamp.
  • Double transition: Two threads that both see the all-red as expired each call next(ctx) on it. The first takes the pedestrian flag and returns the walk phase, and the second finds the flag gone and returns a green. The green is stored last, so the walk lasts zero seconds, and if the stores interleave the green can inherit the walk phase's 12 second end time.
  • Torn picture: Intersection.show() writes four heads and then the walk lamp one after another. A display thread that reads during the change from walk to green can see the north head already green while the walk lamp is still on. No state ever asked for that picture, and violation() would reject it.
  • Caller-applied preemption: If the emergency thread changed the lamps itself while the timer thread entered the next phase, two writers would race for state and the later write could land without the clearance interval between the two pictures.

The Guard and Where It Sits

In Java every entry point of SignalController is a synchronized method (start, tick, requestPedestrian, requestEmergency, vehicleDetected, reportFault, reset, snapshot and addListener), so one monitor serializes all of them. PhaseContext, Intersection and SignalHead carry no locks of their own because nothing outside the controller reaches them. Python wraps the same entry points in with self._lock using a threading.RLock. TypeScript has no lock at all, because Node runs each call to completion on one thread and no method awaits, so one call can never be interleaved with another. If a method ever became asynchronous, that guarantee would end and a queue or a lock would be needed.

The second half of the guard is a rule about what callers may do. The request methods only record a fact and return, and only tick() changes the lamps. That keeps every lock hold short, gives the lamps exactly one writer, and means a request can never put the intersection into a state the phase machine did not choose. A single coarse lock is the right size here. There are four approaches and a handful of events per second, so contention is negligible and the invariant is easy to argue.

The cost is that the lock is held while listeners run, so a slow SignalListener delays every request and the next tick. A production controller hands snapshots to a queue that another thread drains.

What the Blueprint Does Not Guard

  • Timer health: If the timer thread stalls, the lamps stay in whatever phase they were in and nothing notices. A production cabinet has a hardware watchdog that forces flashing red when ticks stop.
  • Clock source: A Clock backed by wall time can jump, and a forward jump would end a yellow early. Production uses a monotonic clock, and the blueprint's manual clock only moves when the driver moves it.
  • Software is the only checker: A stuck relay, a miswired head or a lamp driver bug is invisible to violation(). Real cabinets add an independent conflict monitor that watches the actual field outputs and trips to flashing red by itself.
  • One writer per intersection: Two processes driving the same heads would each be safe alone and unsafe together. Production relies on a hardware interlock or on leader election so only one controller is live.
  • Who may preempt: Anyone who can call requestEmergency can take the intersection, and repeated requests can starve the cross street. Production authenticates the receiver and limits how often one axis may preempt.

A Test That Exposes a Broken Guard

Start eight threads that loop over requestPedestrian, requestEmergency and vehicleDetected, one thread that advances the manual clock and calls tick(), and a checker thread that loops on snapshot() and fails if Intersection.violation() returns anything. Walk phases happen often under that load. Remove synchronized from snapshot() and the checker eventually catches the north head green with the walk lamp still on. For the lost press, press the button exactly once, run one full cycle and count walk phases through a listener. The count must be one, and with synchronized removed from requestPedestrian() and tick() repeated runs eventually report zero.

Complete Clean Code Blueprint

Runnable Reference Designs

The three blueprints implement the same classes and run the same scenario against a manual clock, so the output is identical in Java, TypeScript and Python and no run sleeps. The driver runs the fixed-time plan with three simultaneous pedestrian presses, ambulances from the north and south, a fault and a reset, then runs the actuated plan with queued vehicles, and finally asserts that no snapshot ever showed a conflicting green. Java and Python make the concurrent calls from real threads. TypeScript makes them as consecutive calls, since the event loop has no threads to race.

// โ”€โ”€โ”€ JAVA BLUEPRINT โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
import java.util.*;

enum Axis {
    NORTH_SOUTH("NS"), EAST_WEST("EW");

    final String label;
    Axis(String label) { this.label = label; }
    Axis other() { return this == NORTH_SOUTH ? EAST_WEST : NORTH_SOUTH; }
}

enum Approach {
    NORTH(Axis.NORTH_SOUTH), SOUTH(Axis.NORTH_SOUTH), EAST(Axis.EAST_WEST), WEST(Axis.EAST_WEST);

    final Axis axis;
    Approach(Axis axis) { this.axis = axis; }
    boolean conflictsWith(Approach other) { return axis != other.axis; }
}

enum Light {
    RED('R'), YELLOW('Y'), GREEN('G'), FLASHING_RED('F');

    final char code;
    Light(char code) { this.code = code; }
    boolean proceeds() { return this == GREEN || this == YELLOW; }
}

class SignalHead {
    final Approach approach;
    private Light light = Light.RED;

    SignalHead(Approach approach) { this.approach = approach; }
    Light light() { return light; }
    void set(Light light) { this.light = light; }
}

// Immutable view of the intersection at one instant, safe to hand to observers.
final class Snapshot {
    final String phase;
    final Map<Approach, Light> lights;
    final boolean walk;

    Snapshot(String phase, Map<Approach, Light> lights, boolean walk) {
        this.phase = phase;
        this.lights = Collections.unmodifiableMap(new EnumMap<>(lights));
        this.walk = walk;
    }

    @Override public String toString() {
        StringBuilder sb = new StringBuilder();
        for (Approach a : Approach.values()) {
            sb.append(a.name().charAt(0)).append(':').append(lights.get(a).code).append(' ');
        }
        return sb.append("walk=").append(walk ? "on" : "off").toString();
    }
}

class Intersection {
    private final Map<Approach, SignalHead> heads = new EnumMap<>(Approach.class);
    private boolean walk;

    Intersection() {
        for (Approach a : Approach.values()) heads.put(a, new SignalHead(a));
    }

    // The one place the safety rule lives. Returns null when the picture is safe, else the reason.
    static String violation(Map<Approach, Light> lights, boolean walk) {
        if (lights.size() != Approach.values().length) return "every approach needs a light";
        for (Approach a : Approach.values()) {
            for (Approach b : Approach.values()) {
                if (a.ordinal() < b.ordinal() && a.conflictsWith(b)
                        && lights.get(a).proceeds() && lights.get(b).proceeds()) {
                    return a + " and " + b + " would both proceed";
                }
            }
        }
        if (walk) {
            for (Light light : lights.values()) {
                if (light != Light.RED) return "walk needs every approach red";
            }
        }
        return null;
    }

    void show(Map<Approach, Light> lights, boolean walk) {
        String problem = violation(lights, walk);
        if (problem != null) throw new IllegalStateException(problem);
        lights.forEach((approach, light) -> heads.get(approach).set(light));
        this.walk = walk;
    }

    Snapshot snapshot(String phase) {
        Map<Approach, Light> shown = new EnumMap<>(Approach.class);
        heads.forEach((approach, head) -> shown.put(approach, head.light()));
        return new Snapshot(phase, shown, walk);
    }
}

interface Clock { long nowMs(); }

class ManualClock implements Clock {
    private long now;
    public long nowMs() { return now; }
    void advance(long ms) { now += ms; }
}

interface TimingPlan { long greenMs(Axis axis, int waiting); }

class FixedTimePlan implements TimingPlan {
    private final long greenMs;
    FixedTimePlan(long greenMs) { this.greenMs = greenMs; }
    public long greenMs(Axis axis, int waiting) { return greenMs; }
}

// Sizes each green from the queue seen when it starts: a minimum plus a little per vehicle, capped.
class ActuatedPlan implements TimingPlan {
    private final long minMs, perVehicleMs, maxMs;

    ActuatedPlan(long minMs, long perVehicleMs, long maxMs) {
        this.minMs = minMs;
        this.perVehicleMs = perVehicleMs;
        this.maxMs = maxMs;
    }

    public long greenMs(Axis axis, int waiting) {
        return Math.min(maxMs, minMs + perVehicleMs * waiting);
    }
}

// Pending requests and detector counts. Not thread safe on its own: SignalController's lock guards it.
class PhaseContext {
    private final Deque<Axis> emergencies = new ArrayDeque<>();
    private final Map<Approach, Integer> waiting = new EnumMap<>(Approach.class);
    private final TimingPlan plan;
    private boolean pedestrianWaiting;

    PhaseContext(TimingPlan plan) { this.plan = plan; }

    void requestEmergency(Axis axis) { if (!emergencies.contains(axis)) emergencies.addLast(axis); }
    Axis emergencyAxis() { return emergencies.peekFirst(); }
    Axis takeEmergency() { return emergencies.pollFirst(); }

    void requestPedestrian() { pedestrianWaiting = true; }
    boolean takePedestrian() {
        boolean was = pedestrianWaiting;
        pedestrianWaiting = false;
        return was;
    }

    void vehicleDetected(Approach approach) { waiting.merge(approach, 1, Integer::sum); }

    GreenState green(Axis axis) {
        int queue = 0;
        for (Approach a : Approach.values()) {
            Integer served = a.axis == axis ? waiting.remove(a) : null;
            if (served != null) queue = Math.max(queue, served);
        }
        return new GreenState(axis, plan.greenMs(axis, queue));
    }
}

abstract class PhaseState {
    static final long YELLOW_MS = 4_000;
    static final long ALL_RED_MS = 2_000;
    static final long PEDESTRIAN_MS = 12_000;
    static final long EMERGENCY_HOLD_MS = 10_000;
    static final long FOREVER = Long.MAX_VALUE / 2;

    abstract String name();
    abstract long durationMs();
    abstract Map<Approach, Light> lights();
    abstract PhaseState next(PhaseContext ctx);

    boolean walk() { return false; }

    // Safety intervals are never cut short, so the default ignores the request until the phase ends.
    PhaseState onEmergency(Axis axis, PhaseContext ctx) { return this; }

    static Map<Approach, Light> show(Axis axis, Light on) {
        Map<Approach, Light> lights = new EnumMap<>(Approach.class);
        for (Approach a : Approach.values()) lights.put(a, a.axis == axis ? on : Light.RED);
        return lights;
    }

    static Map<Approach, Light> allShow(Light light) {
        Map<Approach, Light> lights = new EnumMap<>(Approach.class);
        for (Approach a : Approach.values()) lights.put(a, light);
        return lights;
    }
}

class GreenState extends PhaseState {
    private final Axis axis;
    private final long durationMs;

    GreenState(Axis axis, long durationMs) {
        this.axis = axis;
        this.durationMs = durationMs;
    }

    String name() { return axis.label + "_GREEN"; }
    long durationMs() { return durationMs; }
    Map<Approach, Light> lights() { return show(axis, Light.GREEN); }
    PhaseState next(PhaseContext ctx) { return new YellowState(axis); }

    @Override PhaseState onEmergency(Axis emergency, PhaseContext ctx) {
        if (emergency == axis) {
            ctx.takeEmergency();
            return new EmergencyState(axis);
        }
        return new YellowState(axis);
    }
}

class YellowState extends PhaseState {
    private final Axis axis;
    YellowState(Axis axis) { this.axis = axis; }

    String name() { return axis.label + "_YELLOW"; }
    long durationMs() { return YELLOW_MS; }
    Map<Approach, Light> lights() { return show(axis, Light.YELLOW); }
    PhaseState next(PhaseContext ctx) { return new AllRedState(axis); }
}

class AllRedState extends PhaseState {
    private final Axis cleared;
    AllRedState(Axis cleared) { this.cleared = cleared; }

    String name() { return "ALL_RED"; }
    long durationMs() { return ALL_RED_MS; }
    Map<Approach, Light> lights() { return allShow(Light.RED); }

    PhaseState next(PhaseContext ctx) {
        if (ctx.emergencyAxis() != null) return new EmergencyState(ctx.takeEmergency());
        if (ctx.takePedestrian()) return new PedestrianState(cleared.other());
        return ctx.green(cleared.other());
    }
}

class PedestrianState extends PhaseState {
    private final Axis resume;
    PedestrianState(Axis resume) { this.resume = resume; }

    String name() { return "PEDESTRIAN_WALK"; }
    long durationMs() { return PEDESTRIAN_MS; }
    Map<Approach, Light> lights() { return allShow(Light.RED); }
    @Override boolean walk() { return true; }

    PhaseState next(PhaseContext ctx) {
        if (ctx.emergencyAxis() != null) return new EmergencyState(ctx.takeEmergency());
        return ctx.green(resume);
    }
}

class EmergencyState extends PhaseState {
    private final Axis axis;
    EmergencyState(Axis axis) { this.axis = axis; }

    String name() { return axis.label + "_EMERGENCY"; }
    long durationMs() { return EMERGENCY_HOLD_MS; }
    Map<Approach, Light> lights() { return show(axis, Light.GREEN); }
    PhaseState next(PhaseContext ctx) { return new YellowState(axis); }

    @Override PhaseState onEmergency(Axis emergency, PhaseContext ctx) {
        if (emergency != axis) return this;
        ctx.takeEmergency();
        return new EmergencyState(axis);
    }
}

class FlashingRedState extends PhaseState {
    final String reason;
    FlashingRedState(String reason) { this.reason = reason; }

    String name() { return "FLASHING_RED"; }
    long durationMs() { return FOREVER; }
    Map<Approach, Light> lights() { return allShow(Light.FLASHING_RED); }
    PhaseState next(PhaseContext ctx) { return this; }
}

interface SignalListener { void phaseChanged(long atMs, Snapshot snapshot); }

class ConsoleLogger implements SignalListener {
    public void phaseChanged(long atMs, Snapshot s) {
        System.out.printf("t=%3ds  %-15s %s%n", atMs / 1000, s.phase, s);
    }
}

class SignalController {
    private final Intersection intersection = new Intersection();
    private final PhaseContext context;
    private final Clock clock;
    private final List<SignalListener> listeners = new ArrayList<>();
    private PhaseState state;
    private long phaseEndsAtMs;

    SignalController(TimingPlan plan, Clock clock) {
        this.context = new PhaseContext(plan);
        this.clock = clock;
    }

    synchronized void addListener(SignalListener listener) { listeners.add(listener); }

    // Power up in all red, so nobody has right of way until the first clearance interval ends.
    synchronized void start() { enter(new AllRedState(Axis.EAST_WEST)); }

    // Called by the timer thread. Requests wait in the context until this method applies them.
    synchronized void tick() {
        Axis emergency = context.emergencyAxis();
        if (emergency != null) {
            PhaseState preempted = state.onEmergency(emergency, context);
            if (preempted != state) enter(preempted);
        }
        if (clock.nowMs() >= phaseEndsAtMs) enter(state.next(context));
    }

    synchronized void requestPedestrian() { context.requestPedestrian(); }
    synchronized void requestEmergency(Approach from) { context.requestEmergency(from.axis); }
    synchronized void vehicleDetected(Approach from) { context.vehicleDetected(from); }

    // Flashing red gives nobody right of way, so it is safe from any phase and is applied at once.
    synchronized void reportFault(String reason) { enter(new FlashingRedState(reason)); }

    synchronized void reset() {
        if (state instanceof FlashingRedState) enter(new AllRedState(Axis.EAST_WEST));
    }

    synchronized Snapshot snapshot() { return intersection.snapshot(state.name()); }

    private void enter(PhaseState next) {
        try {
            intersection.show(next.lights(), next.walk());
        } catch (IllegalStateException violation) {
            // An unsafe picture never reaches the heads. The controller fails safe instead.
            next = new FlashingRedState("conflict monitor: " + violation.getMessage());
            intersection.show(next.lights(), next.walk());
        }
        state = next;
        phaseEndsAtMs = clock.nowMs() + next.durationMs();
        Snapshot snapshot = intersection.snapshot(next.name());
        for (SignalListener listener : listeners) listener.phaseChanged(clock.nowMs(), snapshot);
    }
}

public class Main {
    static int checked = 0;
    static int violations = 0;

    // Steps the manual clock one second at a time and checks the safety rule after every tick.
    static void run(ManualClock clock, SignalController controller, int seconds) {
        for (int i = 0; i < seconds; i++) {
            clock.advance(1_000);
            controller.tick();
            Snapshot s = controller.snapshot();
            checked++;
            if (Intersection.violation(s.lights, s.walk) != null) violations++;
        }
    }

    static void inParallel(Runnable... jobs) throws InterruptedException {
        List<Thread> threads = new ArrayList<>();
        for (Runnable job : jobs) {
            Thread t = new Thread(job);
            threads.add(t);
            t.start();
        }
        for (Thread t : threads) t.join();
    }

    public static void main(String[] args) throws Exception {
        System.out.println("== Fixed time: 30s green, 4s yellow, 2s all red ==");
        ManualClock clock = new ManualClock();
        SignalController controller = new SignalController(new FixedTimePlan(30_000), clock);
        controller.addListener(new ConsoleLogger());
        controller.start();
        run(clock, controller, 8);

        System.out.println("-- three pedestrians press the button at once");
        inParallel(controller::requestPedestrian, controller::requestPedestrian, controller::requestPedestrian);
        run(clock, controller, 52);

        System.out.println("-- ambulances approach from NORTH and SOUTH while EW is green");
        inParallel(() -> controller.requestEmergency(Approach.NORTH),
                   () -> controller.requestEmergency(Approach.SOUTH));
        run(clock, controller, 40);

        System.out.println("-- detector cabinet loses power");
        controller.reportFault("detector cabinet lost power");
        run(clock, controller, 5);
        controller.reset();
        run(clock, controller, 32);

        System.out.println("\n== Vehicle actuated: 10s minimum, +2s per waiting vehicle, 40s maximum ==");
        ManualClock clock2 = new ManualClock();
        SignalController actuated = new SignalController(new ActuatedPlan(10_000, 2_000, 40_000), clock2);
        actuated.addListener(new ConsoleLogger());
        for (int i = 0; i < 6; i++) actuated.vehicleDetected(Approach.EAST);
        for (int i = 0; i < 4; i++) actuated.vehicleDetected(Approach.WEST);
        actuated.start();
        run(clock2, actuated, 60);

        System.out.println("\n== Safety check ==");
        Map<Approach, Light> everyoneGreen = new EnumMap<>(Approach.class);
        for (Approach a : Approach.values()) everyoneGreen.put(a, Light.GREEN);
        try {
            new Intersection().show(everyoneGreen, false);
        } catch (IllegalStateException e) {
            System.out.println("Unsafe picture rejected: " + e.getMessage());
        }
        System.out.println("Snapshots checked: " + checked + ", conflicting greens seen: " + violations);
        if (violations != 0) throw new AssertionError("a conflicting green was shown");
    }
}

๐Ÿ’ฌReview

Help Us Improve

How helpful was this walkthrough?

Click a star to rate. We actively use this feedback to refine and update our system design content.

Placeholder
Optional but highly appreciated!

Discussion

Share your thoughts, ask questions, or help others.

Loading comments...