LOW LEVEL DESIGN · MACHINE CODING · MEDIUM · 3 OF 42

Design an Elevator System: Low-Level Design with Java Code

A bank of elevators designed and coded step by step: requirements, hall calls versus car calls, the class diagram, splitting the problem into which car answers (a dispatch Strategy with a cost function) and in what order a car stops (the LOOK algorithm with two sorted sets), a tick-based control loop, many button threads feeding one loop, displays as observers, extensions and follow-ups, with full Java 17 code.

Patterns usedStrategyObserverState

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
1 / 19

Press play to hear the narration, or step through at your own pace. The full Java code is below.

Full Java solution

One file, Java 17, 173 lines, with a small main() demo. Save it as ElevatorSystem.java, then run javac ElevatorSystem.java && java ElevatorSystem.

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Queue;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * A bank of elevators: buttons drop requests into a thread-safe queue, one control loop assigns
 * hall calls with a pluggable dispatch strategy, and each car serves its stops with the LOOK algorithm.
 */
public class ElevatorSystem {

    // ---------- the model ----------
    enum Direction { UP, DOWN, IDLE }

    enum DoorState { OPEN, CLOSED }

    /** A press on a hall panel (floor + direction) or inside a car (car + destination floor). */
    sealed interface Request permits HallCall, CarCall {}

    record HallCall(int floor, Direction direction) implements Request {}

    record CarCall(int carId, int floor) implements Request {}

    static final class Car {
        final int id;
        int floor;
        Direction direction = Direction.IDLE;
        DoorState doors = DoorState.CLOSED;
        final TreeSet<Integer> upStops = new TreeSet<>();
        final TreeSet<Integer> downStops = new TreeSet<>();

        Car(int id, int floor) {
            this.id = id;
            this.floor = floor;
        }

        boolean idle() { return upStops.isEmpty() && downStops.isEmpty(); }

        void addStop(int target) {
            if (target > floor) upStops.add(target);
            else if (target < floor) downStops.add(target);
            else if (direction == Direction.DOWN) downStops.add(target);
            else upStops.add(target);
        }

        /** LOOK: keep going while there are stops ahead, then reverse; idle when nothing is left. */
        void chooseDirection() {
            boolean up = !upStops.isEmpty(), down = !downStops.isEmpty();
            if (direction == Direction.UP && !up) direction = down ? Direction.DOWN : Direction.IDLE;
            else if (direction == Direction.DOWN && !down) direction = up ? Direction.UP : Direction.IDLE;
            else if (direction == Direction.IDLE && (up || down)) {
                boolean upCloser = up && (!down || upStops.first() - floor <= floor - downStops.last());
                direction = upCloser ? Direction.UP : Direction.DOWN;
            }
        }

        @Override
        public String toString() { return "Car" + id + "@" + floor + " " + direction; }
    }

    // ---------- strategy and observer ----------
    /** Which car answers a hall call. Swap in zoning, destination dispatch or an energy-saving rule. */
    interface DispatchStrategy { Car choose(List<Car> cars, HallCall call); }

    /** Cost = floors to travel before reaching the caller, with a penalty for cars going the wrong way. */
    static final class NearestSuitableCar implements DispatchStrategy {
        private final int topFloor;

        NearestSuitableCar(int topFloor) { this.topFloor = topFloor; }

        public Car choose(List<Car> cars, HallCall call) {
            Comparator<Car> byCost = Comparator.comparingInt((Car c) -> cost(c, call));
            return cars.stream().min(byCost.thenComparingInt(c -> c.id)).orElseThrow();
        }

        int cost(Car c, HallCall call) {
            int d = Math.abs(c.floor - call.floor());
            if (c.direction == Direction.IDLE) return d;
            boolean onTheWay = c.direction == Direction.UP
                    ? call.floor() >= c.floor
                    : call.floor() <= c.floor;
            if (onTheWay && c.direction == call.direction()) return d;
            return d + 2 * topFloor; // must finish its sweep first
        }
    }

    interface ElevatorListener { void onArrive(Car car, int floor); }

    // ---------- the controller ----------
    private final List<Car> cars = new ArrayList<>();
    private final Queue<Request> inbox = new ConcurrentLinkedQueue<>(); // many buttons, one reader
    private final DispatchStrategy dispatch;
    private final List<ElevatorListener> listeners = new CopyOnWriteArrayList<>();
    private final int floors;

    ElevatorSystem(int carCount, int floors, DispatchStrategy dispatch) {
        for (int i = 1; i <= carCount; i++) cars.add(new Car(i, 0));
        this.floors = floors;
        this.dispatch = dispatch;
    }

    void subscribe(ElevatorListener l) { listeners.add(l); }

    /** Called from any thread (buttons, API). Validation only; the control loop does the rest. */
    void press(Request r) {
        int floor = r instanceof HallCall h ? h.floor() : ((CarCall) r).floor();
        if (floor < 0 || floor >= floors) throw new IllegalArgumentException("No floor " + floor);
        inbox.add(r);
    }

    /** One tick of the control loop: drain requests, then move each car one floor or open its doors. */
    void step() {
        for (Request r; (r = inbox.poll()) != null; ) {
            if (r instanceof HallCall h) dispatch.choose(cars, h).addStop(h.floor());
            else if (r instanceof CarCall c) cars.get(c.carId() - 1).addStop(c.floor());
        }
        for (Car c : cars) move(c);
    }

    private void move(Car c) {
        if (c.doors == DoorState.OPEN) { // doors stay open for one tick
            c.doors = DoorState.CLOSED;
            c.chooseDirection(); // goes IDLE when nothing is left
            return;
        }
        c.chooseDirection();
        if (c.direction == Direction.IDLE) return;
        TreeSet<Integer> ahead = c.direction == Direction.UP ? c.upStops : c.downStops;
        if (ahead.remove(c.floor)) { // a stop at the current floor
            arrive(c);
            return;
        }
        c.floor += c.direction == Direction.UP ? 1 : -1;
        if (ahead.remove(c.floor)) arrive(c);
    }

    private void arrive(Car c) {
        c.doors = DoorState.OPEN;
        for (ElevatorListener l : listeners) l.onArrive(c, c.floor);
    }

    boolean allIdle() { return cars.stream().allMatch(c -> c.idle() && c.doors == DoorState.CLOSED); }

    // ---------- demo ----------
    public static void main(String[] args) throws InterruptedException {
        ElevatorSystem bank = new ElevatorSystem(2, 10, new NearestSuitableCar(9));
        List<String> log = new ArrayList<>();
        bank.subscribe((car, floor) -> log.add("Car" + car.id + " opens at " + floor));

        bank.press(new HallCall(5, Direction.UP)); // someone on 5 wants to go up
        bank.press(new HallCall(2, Direction.UP));
        for (int t = 0; t < 3; t++) bank.step();
        bank.press(new CarCall(1, 9));
        bank.press(new CarCall(2, 7));

        // Buttons pressed from other threads land safely in the queue.
        Thread lobby = new Thread(() -> bank.press(new HallCall(0, Direction.UP)));
        lobby.start();
        lobby.join();

        int ticks = 3;
        while (!bank.allIdle() && ticks < 60) {
            bank.step();
            ticks++;
        }
        log.forEach(System.out::println);
        System.out.println("All idle after " + ticks + " ticks: " + bank.cars);
        if (!bank.allIdle()) throw new AssertionError("requests left unserved");
    }
}

Notes

Requirements

The requirements. A building has N cars and F floors. Each floor has a hall panel with up and down buttons; each car has a panel of destination floors. The system picks a good car for every hall call, cars stop at requested floors on the way, doors open on arrival, and displays show where each car is. Buttons are pressed from many places at once. Weight limits and fire mode are out of scope for the first pass.

Ask what good means. Are we minimising waiting time or energy? Waiting time. Can a call be reassigned to another car later? Not in version one. Should the code run in real time or as a simulation? A simulation with ticks, where a car moves one floor per tick, keeps it testable and deterministic. And how big is the building? A handful of cars and under a hundred floors, so simple loops over cars are fine.

Requirements
  • N cars, F floors
  • hall panel: up or down button
  • on each floor
  • car panel: a destination floor
  • pick a good car for each call
  • stop at floors on the way
  • doors open on arrival
  • displays show car position
  • buttons pressed concurrently
  • out of scope: weight sensors
Clarify first
  • optimise wait time or energy?
  • average wait time
  • can a car skip a hall call?
  • only if another car takes it
  • reassign calls later?
  • not in version one
  • a simulation or real time?
  • ticks: one floor per tick
  • how many cars and floors?
  • 2 to 8 cars, under 100 floors

Entities

The entities. A request is either a hall call, a floor plus a direction, or a car call, a car plus a destination floor. They are different shapes, so model them as a sealed interface with two records, and the compiler knows those are the only kinds. The system owns the cars. Each car knows its floor, its direction, whether its doors are open, and the set of floors it must still visit.

Class diagram

In code: a direction enum with up, down and idle. A sealed request interface permitting exactly two records, hall call and car call. And a car class with its floor, direction, door state, and two sorted sets of stops: floors above it to visit on the way up, and floors below it for the way down. Sorted sets give the next stop in either direction in logarithmic time.

Core types
enum Direction { UP, DOWN, IDLE }
sealed interface Request
    permits HallCall, CarCall {}
record HallCall(int floor, Direction d)
record CarCall(int carId, int floor)

class Car {
  int floor; Direction direction;
  DoorState doors;
  TreeSet<Integer> upStops, downStops;
}

Two decisions

Here is the key design move. There are two independent decisions. First, which car should answer a hall call: that is dispatching, it looks at all cars, and it is a policy the building owner may want to tune. Second, in what order a single car visits its stops: that is scheduling, and it only looks at one car. Keeping them in separate classes means you can change one without breaking the other.

Scheduling: LOOK

For scheduling, first come first served is a disaster: a car at floor five serving nine, two, eight, three in arrival order zigzags twenty-two floors. The LOOK algorithm, borrowed from disk scheduling, keeps moving in its current direction while there are stops ahead, then reverses. The same requests take eleven floors. It is fair, too: nobody waits more than one full sweep.

With two sorted sets, LOOK is a few lines. Adding a stop puts it in the up set if it is above the car and in the down set if below. Each tick the car checks: going up with nothing left above? Turn down if there is anything below, otherwise go idle. The same for going down. An idle car heads toward whichever stop is closer. That is the entire per-car scheduler.

Why not first come first served?
  • car at 5, requests: 9, 2, 8, 3
  • FCFS: 5-9-2-8-3 = 4+7+6+5
  • = 22 floors of travel
  • LOOK: up 8, 9 then down 3, 2
  • = 4 + 7 = 11 floors
  • LOOK = sweep one way while
  • stops remain ahead, then
  • reverse; never runs to the
  • top floor for nothing
Car.chooseDirection()
up = !upStops.isEmpty()
down = !downStops.isEmpty()
if (dir == UP && !up)
  dir = down ? DOWN : IDLE
else if (dir == DOWN && !down)
  dir = up ? UP : IDLE
else if (dir == IDLE && (up || down))
  dir = toward the closer stop

addStop(f): f above -> upStops,
  below -> downStops

Strategy: dispatch

Dispatching is a Strategy with one method: choose a car for this hall call. Our default gives each car a cost. An idle car costs its distance. A car already moving toward the caller in the same direction also costs its distance, because it will pass by anyway. Any other car must finish its sweep first, so it gets a big penalty. The cheapest car wins. Zoning or energy-saving rules are just other strategies.

NearestSuitableCar.cost()
d = |car.floor - call.floor|
idle car: cost = d
moving toward the caller in
  the same direction: cost = d
otherwise: d + 2 * topFloor
  (it must finish its sweep)

ties: lowest car id
swap in: zoning, energy saving,
  destination dispatch

Flow: a hall call

Follow one hall call. Someone on floor five presses up. The button handler validates the floor and drops a hall call into the request queue, then returns immediately. On the next tick, the control loop drains the queue, asks the dispatch strategy which car should go, and adds floor five to that car's stops. From then on it is just that car's LOOK scheduler. A car call skips dispatch and goes straight to its own car.

The control loop

The control loop runs one tick at a time. It drains every pending request and assigns them. Then it moves each car: if the doors are open, close them this tick. Otherwise choose a direction, and if there is a stop at the current floor open the doors, or else move one floor and open the doors if that floor was a stop. A tick model makes the simulation deterministic, so tests can step it and assert exact positions.

step()
for (r; (r = inbox.poll()) != null;)
  hall call -> dispatch.choose(..)
  car call  -> that car
for (Car c : cars) move(c):
  doors open? close them, return
  chooseDirection(); idle? return
  stop here? open doors
  else floor += 1 or -1
  arrived at a stop? open doors

Concurrency

Concurrency is where this design shines. Buttons are pressed from many threads, but those threads never touch a car. They only validate and put a request in a lock-free concurrent queue. Exactly one thread, the control loop, reads that queue and owns all car state. Because only one thread ever writes to the cars, the car class needs no locks at all, and there is no lock ordering to get wrong and no deadlock to debug.

Single writer to car state
  • button threads: press() only
  • validates and enqueues
  • ConcurrentLinkedQueue:
  • lock-free, many producers
  • control loop: the only thread
  • that reads or writes cars
  • so Car needs no locks at all
  • no lock ordering, no deadlocks

Observer: displays

Floor displays, the arrival chime and an audit log all want to know when a car arrives. That is the Observer pattern again: they register an elevator listener, and the system calls them when doors open. The listener list is copy-on-write, so new displays can subscribe while the loop is running. The scheduling code never needs to know how many screens are in the lobby.

Safety

Put the safety rules in the structure, not in comments. A car never moves while its doors are open, because move closes the doors and returns before anything else. Cars move exactly one floor per tick, so they never stop between floors. An invalid floor is rejected before it ever reaches the queue. An emergency stop would be a new mode that clears every stop and opens doors at the nearest floor.

Safety rules in the model
  • never move with doors open:
  • move() closes doors first
  • never stop between floors:
  • one floor per tick
  • invalid floor: rejected in
  • press(), before queueing
  • emergency stop: a new mode
  • that clears all stops

Extensibility

Extending it. A full car should skip new hall calls, so dispatch checks capacity. Tall buildings use express zones, which is a zoning dispatch strategy. Destination dispatch, where riders choose their floor in the lobby, groups riders going to the same floors into one car. Re-running dispatch every tick allows reassigning calls. Fire service and maintenance become per-car modes, a natural place for the State pattern.

Extension points
  • capacity: skip hall calls when
  • the car is full
  • express zones: a zoning
  • DispatchStrategy
  • destination dispatch: riders
  • pick a floor in the lobby
  • reassign calls each tick
  • fire mode / maintenance:
  • per-car State objects

Testing

The full code is below. The demo presses hall calls on floors five and two, lets a few ticks pass, adds car calls to nine and seven, and presses the lobby button from a separate thread. Car one picks up at two and five on the way up and delivers to nine; car two serves the lobby and goes to seven. Everything is idle after thirteen ticks, and the program asserts nothing was left unserved.

Run it
HallCall(5, UP), HallCall(2, UP)
Car1 opens at 2
Car2 opens at 0   (lobby call)
Car1 opens at 5
Car1 opens at 9   (rider chose 9)
Car2 opens at 7
All idle after 13 ticks:
  [Car1@9 IDLE, Car2@7 IDLE]

Follow-ups

Expect follow-ups. Why LOOK and not SCAN? SCAN runs to the last floor even when nobody is there; LOOK turns at the last stop. Can a rider starve? No, every stop is served within one sweep. A car breaks down? Mark it out of service and move its hall calls to other cars. Morning rush? Park idle cars at the lobby. Real time? A scheduled executor calls step every second.

Follow-ups to expect
  • why LOOK and not SCAN?
  • no trip to the end floor
  • starvation? at most one sweep
  • a car breaks down?
  • move its stops to others
  • peak hours? park idle cars
  • at the lobby in the morning
  • real time instead of ticks?
  • a scheduler fires step()

Say it like this

The short version. Buttons enqueue sealed request records into a concurrent queue. One control loop owns all car state, so cars need no locks. A dispatch strategy picks the cheapest car for each hall call, and each car runs the LOOK algorithm over two sorted stop sets. A tick model keeps it deterministic and testable, and displays are observers.

In the interview
  • "Buttons enqueue sealed
  • requests; one control loop owns
  • all car state, so cars need no
  • locks. A dispatch strategy
  • picks the cheapest car; each
  • car runs LOOK with two sorted
  • stop sets. Ticks keep it
  • testable; displays observe."

Interview questions

What are the two main decisions in an elevator system?

Dispatching (which car answers a hall call, looking at all cars) and scheduling (the order one car visits its stops). Keeping them in separate classes lets you tune the dispatch policy without touching per-car movement.

Why use the LOOK algorithm instead of first come, first served?

FCFS zigzags and wastes travel. LOOK keeps moving in one direction while stops remain ahead, then reverses, which roughly halves travel in typical cases and bounds waiting to one sweep, so no rider starves.

How do you implement LOOK efficiently?

Keep two sorted sets per car: stops above the car for the upward sweep and stops below for the downward sweep. TreeSet gives the next stop in log time, and the direction flips when the set ahead is empty.

How does the dispatcher pick a car?

A cost function: an idle car costs its distance, a car moving toward the caller in the same direction costs its distance, any other car pays a penalty for finishing its sweep. The cheapest car wins, and the whole rule sits behind a DispatchStrategy interface.

How do you handle buttons pressed from many threads?

Button threads only validate and add a request to a ConcurrentLinkedQueue. One control loop drains the queue and is the only thread that reads or writes car state, so cars need no locks and deadlocks are impossible.

Why model requests as a sealed interface?

Hall calls and car calls carry different data. A sealed interface with two records lets the compiler know these are the only kinds, so pattern matching on them is safe and a new kind forces every handler to be updated.

How would you test the scheduler?

Use a tick-based step() instead of real time. Tests press buttons, call step a fixed number of times, and assert car floors, door states and the order of arrivals, with no sleeping or flaky timing.

What happens when a car goes out of service?

Mark it unavailable so dispatch skips it, and move its pending hall calls back through dispatch to other cars. Car calls inside the broken car are cancelled and the riders are let out at the nearest floor.