0%
Requirements
Define Core Objects
Analyze Relationships
Establish Hierarchy
Direction Enum
TrafficLightState Interface
Concrete States
Design Patterns
State Pattern: Behavior Through Object Replacement
Observer Pattern: Cross-Light Coordination
Strategy Pattern: Timer Scheduling
Define Class Members / Write Code
TrafficLight
TrafficTimer
Intersection with Thread Safety
Run and Test
Adhere to SOLID Guidelines
Consider Scalability and Flexibility
Atomic State Transitions
City-Wide Scaling
Adaptive Timing
Green Wave Coordination
Create/Explain Your Diagrams
Future Improvements
A traffic light seems like three colored bulbs on a timer. But a real traffic light system must coordinate multiple lights at an intersection to prevent conflicting greens (a safety-critical invariant), handle emergency vehicle overrides that preempt normal cycling, synchronize pedestrian crossing signals, and ensure that state transitions across all lights happen atomically. The design challenge is modeling concurrent state machines that must agree on a safe global state at all times.
Interview Dialogue
Functional Requirements
Non-Functional Requirements
Emergency override is not just a faster normal transition. It is a safety preemption path that must take ownership of the whole intersection state. If one direction is forced GREEN without atomically forcing the others to RED, the code may keep running while the intersection becomes unsafe.
Walk through an intersection and identify the objects. Start with a scenario rather than a noun list.
Scenario: North light is GREEN. The timer fires. North transitions to YELLOW. After 5 seconds, North transitions to RED. Simultaneously, East transitions from RED to GREEN. What objects did the system need?
The timer needed to know how long to wait (a state with a duration). The transition needed to know what comes next (a state with a successor). The intersection needed to coordinate two lights atomically (a coordinator with a lock). These needs point to TrafficLightState (encapsulates duration and successor), Intersection (coordinates lights under a lock), and TrafficTimer (schedules callbacks).
Start by scanning the requirements for nouns. "Traffic light" with "direction" and "current state" gives us TrafficLight and TrafficLightState. "Intersection with multiple lights" becomes Intersection. "Timer" that fires callbacks maps to TrafficTimer. Not every noun becomes a class. "duration" is an attribute of a state, not its own entity, but nouns give you the starting lineup.
Each traffic light has a direction (NORTH, SOUTH, EAST, WEST) and a current state (RED, GREEN, YELLOW). The state determines how long the light stays in that color and what comes next. That gives us a TrafficLight with a direction and a TrafficLightState object.
Why a State object instead of an enum? An enum represents the color (RED, GREEN, YELLOW). But each color has behavior: its duration and which color comes next. A State object encapsulates both the identity (which color) and the behavior (how long, what next). This is the State pattern.
The Intersection manages a group of TrafficLights. It ensures the safety invariant: only one direction is GREEN at a time. It coordinates transitions so that when one direction goes from GREEN to YELLOW to RED, the next direction goes from RED to GREEN.
A TrafficTimer handles scheduling using a ScheduledExecutorService. It fires callbacks when the current state's duration expires. It supports cancel (for emergency overrides) and reset (for resuming normal cycling).
A Direction enum (NORTH, SOUTH, EAST, WEST) identifies each light. The Intersection uses Direction as the key in its light registry.
Composition: Intersection owns TrafficLights
A TrafficLight is a physical light at this specific intersection. It does not exist independently. If the intersection is decommissioned, its lights go with it. The light's lifecycle is bound to the intersection.
State Pattern: TrafficLight has-a TrafficLightState
TrafficLight holds a reference to its current state object. The state determines behavior (duration, next state). When the light transitions, the current state is replaced with its successor. This is the State pattern: behavior changes by swapping the state object, not by adding conditionals.
Composition: Intersection owns TrafficTimer
The timer exists to serve this intersection. It schedules transitions for this intersection's lights. If the intersection shuts down, the timer shuts down with it.
Observer: TrafficLight notifies Intersection
When a TrafficLight transitions, the Intersection needs to know so it can trigger corresponding transitions on other lights. The Observer pattern decouples the notification: TrafficLight fires an event, and Intersection handles it.
Why does the Intersection coordinate lights instead of letting each TrafficLight cycle independently? Independent cycling cannot enforce the safety invariant: two perpendicular lights could both go GREEN simultaneously. Centralized coordination guarantees that only one direction is GREEN at any time.
Delegation: Intersection delegates timing to TrafficTimer
Intersection does not manage time directly. It tells the timer "call me back in N seconds." The timer handles the scheduling mechanics (ScheduledExecutorService). Intersection handles the transition logic.
Four compass directions. Used as keys in the Intersection's light registry.
Why State objects instead of a simple enum with a switch statement? A switch on an enum scatters behavior across every method that checks the color. Adding a FlashingYellow state means editing every switch. A State object encapsulates duration, successor, and name in one class, so adding a new state is one new file with zero changes to existing code.
Three methods, each focused on one concern. next() returns the successor state. getDuration() returns how long this state lasts. getName() returns the color name for display and logging.
Each state carries the duration parameters for all states so it can construct its successor:
GreenState.next() returns YellowState. YellowState.next() returns RedState. The cycle is encoded in the state objects themselves, not in an external controller. This means adding a FlashingYellowState only requires implementing the interface and updating one state's next() method.
Why does each state construct its successor via next() instead of the Intersection managing transitions in a lookup table? A lookup table centralizes all transition logic in one place, but every new state requires editing the table. When each state constructs its own successor, the transition knowledge is colocated with the state that owns it, and adding FlashingYellowState only touches FlashingYellowState.java.
Without the State pattern, TrafficLight would have switch statements in every method:
Adding FlashingYellow means adding a case to every switch. The State pattern replaces this with:
TrafficLight becomes a one-line delegator. Adding FlashingYellowState requires zero changes to TrafficLight.
When a light transitions from GREEN to YELLOW, the Intersection needs to schedule the next direction's transition. The Observer pattern allows TrafficLight to notify the Intersection without knowing about intersection-level coordination logic.
The TrafficTimer is a scheduling strategy. The Intersection tells it "call me back in N seconds" without knowing whether the timer uses ScheduledExecutorService, a hardware clock, or a simulation clock. This decoupling enables unit testing with a mock timer that fires instantly.
The State pattern is safety-critical here. Adding a new state to a switch-based system risks forgetting a case in one of the methods. The State pattern makes the compiler enforce completeness: every state must implement next(), getDuration(), and getName().
Code the state objects and Intersection transition lock before worrying about the real timer. Once state progression and atomic coordination are correct, the timer becomes an injectable scheduling detail instead of the place where safety logic accidentally leaks.
TrafficLight is the thinnest class in the system. It holds a direction and a current state, and delegates everything to the state object.
TrafficLight is a thin wrapper. transition() delegates to the current state's next() method. setState() allows the Intersection to force a state during emergency override. Notice that TrafficLight never contains a switch statement. All behavior comes from the injected state.
The timer bridges the gap between the state machine and real-world time. It does not know about lights or intersections. It only knows how to schedule and cancel callbacks.
Intersection is the coordinator that ties everything together. It owns the lights, owns the timer, and holds the lock that serializes all state-changing operations.
Every method that changes light states acquires the transitionLock. The timer callback also acquires this lock, so timer-triggered transitions and emergency overrides never interleave.
Browse the complete solution code and run it. Try modifying the code to experiment with the design.
Single Responsibility Principle
Open/Closed Principle
Liskov Substitution Principle
Interface Segregation Principle
Dependency Inversion Principle
In interviews, emphasize the safety angle of OCP: 'Adding a new traffic light state to switch statements risks forgetting a case, which in a traffic system could mean undefined behavior at a live intersection. The State pattern makes the compiler enforce completeness.'
The Intersection uses a ReentrantLock to serialize all methods that change light states. start(), transitionLights(), emergencyOverride(), and cancelOverride() all acquire the lock before modifying any light. This guarantees that all lights are in a consistent, safe state at every observable moment.
The race condition, made concrete: North is GREEN, East is RED. The timer fires to transition North.
Without the lock, the timer thread and emergency thread interleave freely. The lock ensures the timer callback either completes fully before the override starts, or the override completes fully before the callback acquires the lock.
For a city managing hundreds of intersections, each Intersection runs on its own timer thread with its own lock. Intersections are independent, so no cross-intersection locking is needed. A city with 5,000 intersections has 5,000 independent state machines running in parallel.
Vehicle sensors or cameras measure traffic density. The system adjusts GREEN duration dynamically: longer for heavy traffic directions, shorter for light traffic. The State pattern makes this straightforward: when constructing the next GreenState, pass a dynamically computed duration instead of a fixed one.
Adjacent intersections can coordinate so that vehicles traveling at the speed limit hit consecutive GREEN lights. This requires inter-intersection communication. Each intersection reports its current state and schedule. A coordinator computes offset timings so that GREEN phases propagate along a corridor like a wave.
Junior: explain the State pattern and why conflicting greens are dangerous.
Mid-level: design the emergency override with atomic lock acquisition and timer cancellation.
Senior: discuss adaptive timing with sensor input and green wave coordination across multiple intersections.
Why fine-grained locking instead of a single global lock? A global lock serializes all operations - only one thread can do anything at a time. Per-resource locks let operations on different resources proceed in parallel, scaling throughput linearly with the number of independent resources.
Below is the class diagram for the traffic light system.
Key points to highlight in an interview:
Adaptive Timing with Sensors
Use vehicle sensors or cameras to measure traffic density. Adjust GREEN duration dynamically: longer for heavy traffic directions, shorter for light traffic. Machine learning models can optimize signal timing across entire corridors based on historical and real-time data.
Green Wave Coordination
Coordinate adjacent intersections so vehicles traveling at the speed limit hit consecutive GREEN lights. This requires inter-intersection communication and offset timing calculations. The result is smoother traffic flow and reduced stop-and-go patterns.
Monitoring Dashboard
A central dashboard shows real-time state of all intersections in the city. Detects stuck lights (a light that has not transitioned in twice its maximum duration), communication failures, and abnormal patterns. Alerts operators for manual intervention when automated systems fail.
Left-Turn Arrow Phases
Complex intersections need protected left-turn phases. An ArrowGreenState allows left turns while perpendicular traffic is held RED. The State pattern makes this a new state class with no changes to existing code.
Vehicle-to-Infrastructure (V2I) Communication
Connected vehicles report their position, speed, and intended direction. The intersection uses this data for proactive timing adjustments and direct communication with vehicles about upcoming signal changes, enabling smoother deceleration and fewer sudden stops.
Reading a solution is not the same as producing one under interview pressure. Design it on the whiteboard and get scored feedback.
0%
Requirements
Define Core Objects
Analyze Relationships
Establish Hierarchy
Direction Enum
TrafficLightState Interface
Concrete States
Design Patterns
State Pattern: Behavior Through Object Replacement
Observer Pattern: Cross-Light Coordination
Strategy Pattern: Timer Scheduling
Define Class Members / Write Code
TrafficLight
TrafficTimer
Intersection with Thread Safety
Run and Test
Adhere to SOLID Guidelines
Consider Scalability and Flexibility
Atomic State Transitions
City-Wide Scaling
Adaptive Timing
Green Wave Coordination
Create/Explain Your Diagrams
Future Improvements