LLD

Full Designs

Parking Lot

This is the most asked low-level design question. A weak answer lists ten classes and stops. We build one that holds up when the interviewer pushes: which spot a car gets, how the fee is calculated, what happens when two gates take the last spot at once, and what happens when a card is declined.

"Design a parking lot" is the most common low-level design question. Most candidates draw a ParkingLot, a Floor, a Spot, a Vehicle with Car and Truck under it, and a Ticket. Then they stop. The class names are right, and almost nothing has been designed.

The interviewer is not checking whether you know that a parking lot has spots. They want to see how you turn a vague request into a few classes with clear jobs, and how you defend the choices underneath: who decides which spot a car gets, where the "is this spot free?" information lives, what happens when two cars arrive at two gates for the last spot, and what happens when a payment fails at the exit.

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.

The lot at a glance
At the entry gate (1), ParkingLot asks the allocation strategy for a spot and issues a ticket with the spot and the time on it (2). At the exit gate (3), the pricing strategy turns the time parked into a fee, and the payment processor charges it (4). Only after the charge succeeds does the floor get its spot back (5). Every change in free spots goes out to the display boards (6).At the entry gate (1), ParkingLot asks the allocation strategy for a spot and issues a ticket with the spot and the time on it (2). At the exit gate (3), the pricing strategy turns the time parked into a fee, and the payment processor charges it (4). Only after the charge succeeds does the floor get its spot back (5). Every change in free spots goes out to the display boards (6).
A car gets a spot and a ticket at the entry, and pays with that ticket at the exit. At the entry gate (1), ParkingLot asks the allocation strategy for a spot and issues a ticket with the spot and the time on it (2). At the exit gate (3), the pricing strategy turns the time parked into a fee, and the payment processor charges it (4). Only after the charge succeeds does the floor get its spot back (5). Every change in free spots goes out to the display boards (6).

Ask before you design

The question is vague on purpose. Asking good questions in the first five minutes is part of what is being graded. Each question below changes the code, and the right-hand column says how.

QuestionWhat we assumeWhat it changes
One building or many?One lot, several floorsA ParkingLot with a list of ParkingFloor
What vehicles?Motorcycles, cars, trucksA VehicleType enum with three values
What spot sizes?Small, medium, largeA SpotSize enum
Can a small vehicle use a big spot?Yes. By default, only when no spot of its own size is free on any floorThe allocation rule, which the owner may want to change
How many gates?Several entries and several exits, used at the same timeThe code must be safe when called from many threads
How is the fee calculated?An hourly rate per vehicle type, each started hour charged in fullA pricing class, and the rule may change later
How does a driver pay?Card at the exit, through an outside payment systemAn interface for payments
Do drivers book in advance?No, first come first servedNo reservations in this version
Is there a board showing free spots?Yes, at each entrance, per floor and sizeSomething must tell the boards when counts change

The last column matters most. "How many gates?" sounds like a detail, but the answer means two cars can be given a spot at the same instant, and the design must make sure they never get the same one.

Requirements

Functional:

  1. A vehicle arriving at any entry gets a free spot that fits it, and a ticket. If nothing fits, it is turned away.
  2. A vehicle leaving at any exit pays a fee based on its type and how long it stayed. Its spot becomes free only after payment succeeds.
  3. Each ticket can be used to leave exactly once.
  4. Entrance boards show the free spots per floor and size, and stay current.

Out of scope: reservations, monthly passes, EV charging, lost tickets, and number-plate cameras. We come back to each of these at the end, because interviewers often ask about them as follow-ups. A design that is easy to extend in those directions is part of the answer.

Everything lives in memory, as is normal for a low-level design interview. Saving tickets so they survive a restart is a storage question for a separate discussion.

What the code itself must handle:

  • Many gates at once. park and leave will be called from several threads together.
  • Rules that change. The way spots are chosen and the way fees are calculated will change. Changing them should not mean editing the core classes.
  • Testable. Fees depend on time, so a test must be able to control the clock.

Finding the classes

A common way to start is to read the requirements and pick out the nouns. Most nouns become classes. Some do not, and dropping them is as much a part of the design as keeping the others.

From nouns to classes
Lot, floor, spot, vehicle, ticket and fee become classes or enums. The gate, the barrier, the driver and the card are crossed out. A gate is a place where code calls park() or leave(), so it has no behaviour of its own. The barrier and the driver are outside the software. The card is the payment system's business, so we keep only an interface to it.Lot, floor, spot, vehicle, ticket and fee become classes or enums. The gate, the barrier, the driver and the card are crossed out. A gate is a place where code calls park() or leave(), so it has no behaviour of its own. The barrier and the driver are outside the software. The card is the payment system's business, so we keep only an interface to it.
Most nouns in the requirements become classes. Some should not. Lot, floor, spot, vehicle, ticket and fee become classes or enums. The gate, the barrier, the driver and the card are crossed out. A gate is a place where code calls park() or leave(), so it has no behaviour of its own. The barrier and the driver are outside the software. The card is the payment system's business, so we keep only an interface to it.

Two of the kept nouns are not plain data. Choosing a spot and calculating a fee are rules, and the requirements say these rules will change. Rules that change get an interface, so that a new rule is a new class and nothing else is edited. That gives us two strategies: SpotAllocationStrategy and PricingStrategy.

Decision

Should a gate be a class?

EntryGate and ExitGate classes

Many answers have them, because "gate" appears in the question. Here they would hold an id and call lot.park() or lot.leave(), and do nothing else. A class with no behaviour of its own adds a file to read and a layer to step through.

No gate classes. A gate is just a caller of ParkingLotOur pick

Gates matter because several of them work at the same time. That is a concurrency requirement on ParkingLot, not a reason for a class. If gates later need their own behaviour, such as a gate that only lets trucks in, we add the class then.

Data or behaviour?

Some classes only carry data and never change once created: a vehicle, a spot, a ticket, a receipt. In Java these are records. A record is a class whose fields are fixed when it is created and which gets equals, hashCode and toString for free. Using records makes it clear which classes have no logic.

ticket/Ticket.javalines 8–9 of 9
public record Ticket(String id, Vehicle vehicle, ParkingSpot spot, Instant entryTime) {}

ParkingSpot is a record too: an id, a floor number and a size. It has no "is free" flag, and that is deliberate. We will see why in a moment.

The class diagram

The classes and how they connect
ParkingLot owns its floors and the map of active tickets. It holds a SpotAllocationStrategy, a PricingStrategy and a PaymentProcessor as interfaces, so each can be swapped without touching ParkingLot. Each ParkingFloor owns the free-spot lists for its spots. Vehicle, ParkingSpot, Ticket and Receipt are records: data with no behaviour. Listeners hear about every change in free spots.ParkingLot owns its floors and the map of active tickets. It holds a SpotAllocationStrategy, a PricingStrategy and a PaymentProcessor as interfaces, so each can be swapped without touching ParkingLot. Each ParkingFloor owns the free-spot lists for its spots. Vehicle, ParkingSpot, Ticket and Receipt are records: data with no behaviour. Listeners hear about every change in free spots.
ParkingLot coordinates. The floors own the spots. Two strategies hold the rules that change. ParkingLot owns its floors and the map of active tickets. It holds a SpotAllocationStrategy, a PricingStrategy and a PaymentProcessor as interfaces, so each can be swapped without touching ParkingLot. Each ParkingFloor owns the free-spot lists for its spots. Vehicle, ParkingSpot, Ticket and Receipt are records: data with no behaviour. Listeners hear about every change in free spots.

The classes fall into three groups:

  • Data: Vehicle, VehicleType, ParkingSpot, SpotSize, Ticket, Receipt. These are records and enums, with no behaviour beyond small helpers.
  • The core: ParkingLot and ParkingFloor. These hold the changing state (who is parked where) and keep it correct under many threads.
  • Rules and outside systems: SpotAllocationStrategy, PricingStrategy, PaymentProcessor and AvailabilityListener. All four are interfaces. The core depends on these interfaces and never on a specific implementation.

The rest of the article builds these one at a time.

Building it

Vehicles and spot sizes

A motorcycle fits in any spot. A car fits in a medium or large spot. A truck needs a large one. The simplest way to say this is to give each vehicle type its smallest fitting size, and list the sizes in order:

spot/SpotSize.javalines 3–8 of 8
// Declared smallest first. VehicleType.fittingSizes() relies on this order.public enum SpotSize {    SMALL,    MEDIUM,    LARGE}
vehicle/VehicleType.javalines 8–28 of 28
public enum VehicleType {    MOTORCYCLE(SpotSize.SMALL),    CAR(SpotSize.MEDIUM),    TRUCK(SpotSize.LARGE);     private final SpotSize smallestFit;     VehicleType(SpotSize smallestFit) {        this.smallestFit = smallestFit;    }     public List<SpotSize> fittingSizes() {        List<SpotSize> sizes = new ArrayList<>();        for (SpotSize size : SpotSize.values()) {            if (size.compareTo(smallestFit) >= 0) {                sizes.add(size);            }        }        return sizes;    }}

fittingSizes() returns every size the vehicle fits, smallest first. A car gets [MEDIUM, LARGE]. The order matters: the allocation strategy tries the sizes in this order, so a car takes a medium spot before a large one.

Decision

Car, Truck and Motorcycle subclasses, or one enum?

A Vehicle base class with a subclass per type

This is what most answers draw. But the subclasses would contain nothing except their own type. No method behaves differently for a car than for a truck. Inheritance used only to label things gives you three classes to keep in step and a type check wherever the type matters.

One Vehicle record with a VehicleType enumOur pick

The type is data, so it is a field. The enum holds what differs between types, which is the spots each one fits. Adding a bus is one new line in the enum. If a type ever needs different behaviour, a subclass can come then, with a real reason.

A floor and its free spots

The next question is where "is this spot free?" lives. The obvious answer is a boolean occupied on every spot. Then finding a free spot means scanning every spot on every floor, and two gates scanning at once can both see the same spot as free.

Instead, each floor keeps a list of its free spots for each size. Taking a spot removes it from the list. Releasing a spot adds it back.

lot/ParkingFloor.javalines 12–47 of 52
public class ParkingFloor {    private final int number;    private final Map<SpotSize, Deque<ParkingSpot>> freeSpots = new EnumMap<>(SpotSize.class);     public ParkingFloor(int number, Map<SpotSize, Integer> spotCounts) {        this.number = number;        int spotNumber = 1;        for (SpotSize size : SpotSize.values()) {            Deque<ParkingSpot> spots = new ArrayDeque<>();            int count = spotCounts.getOrDefault(size, 0);            for (int i = 0; i < count; i++) {                spots.addLast(new ParkingSpot(spotId(spotNumber), number, size));                spotNumber++;            }            freeSpots.put(size, spots);        }    }     public int number() {        return number;    }     public synchronized Optional<ParkingSpot> takeSpot(SpotSize size) {        return Optional.ofNullable(freeSpots.get(size).pollFirst());    }     public synchronized void releaseSpot(ParkingSpot spot) {        if (spot.floor() != number) {            throw new IllegalArgumentException(spot.id() + " is not on floor " + number);        }        freeSpots.get(spot.size()).addLast(spot);    }     public synchronized int freeSpots(SpotSize size) {        return freeSpots.get(size).size();    }

The floor creates its own spots from a count per size, and gives them ids like F1-03. Then three methods do all the work, and all three are synchronized:

  • takeSpot(size) removes the first free spot of that size and returns it, or returns empty if there is none. Finding a spot and marking it taken happen in one step, so two threads can never take the same spot.
  • releaseSpot(spot) puts a spot back.
  • freeSpots(size) counts, for the display boards.
Decision

Where does a spot's free or taken status live?

An occupied flag on each ParkingSpot

This is easy to picture. But finding a spot means a scan, the flag and the ticket can disagree, and checking "is it free?" then setting "now it is taken" are two steps. Another thread can slip in between them.

Free-spot lists on the floor, and nothing on the spotOur pick

A spot is free if and only if it is in its floor's free list. There is one source of truth, taking a spot is a single pollFirst() under the floor's lock, and the spot itself can be an unchangeable record. The ticket records which car is in a taken spot, and nothing else needs to know.

Choosing a spot

Which free spot should a car get? There is more than one good answer, and the business will want to change its mind. This is the first place the design needs a pattern.

Here is the interface:

allocation/SpotAllocationStrategy.javalines 10–12 of 12
public interface SpotAllocationStrategy {    Optional<ParkingSpot> allocate(List<ParkingFloor> floors, VehicleType type);}

An implementation gets the floors and a vehicle type, and returns a spot it has already taken. It takes the spot with floor.takeSpot(), so choosing and taking cannot be split by another thread.

Here is the default rule. It tries the smallest fitting size on every floor before it tries a bigger size anywhere:

allocation/SmallestSpotFirst.javalines 11–24 of 24
public class SmallestSpotFirst implements SpotAllocationStrategy {    @Override    public Optional<ParkingSpot> allocate(List<ParkingFloor> floors, VehicleType type) {        for (SpotSize size : type.fittingSizes()) {            for (ParkingFloor floor : floors) {                Optional<ParkingSpot> spot = floor.takeSpot(size);                if (spot.isPresent()) {                    return spot;                }            }        }        return Optional.empty();    }}

The two loops can go the other way round. LowestFloorFirst loops over floors on the outside, so it fills the lowest floor first, using bigger spots if it has to. Swapping two loops changes where every vehicle ends up:

Same lot, same motorcycle, two rules
Floor 1 has no small spot free, and floor 2 does. SmallestSpotFirst sends the motorcycle up to floor 2's small spot, keeping floor 1's medium spot for a car. LowestFloorFirst parks it in floor 1's medium spot. Later, a car that would have used that spot has to go up to floor 2 instead.Floor 1 has no small spot free, and floor 2 does. SmallestSpotFirst sends the motorcycle up to floor 2's small spot, keeping floor 1's medium spot for a car. LowestFloorFirst parks it in floor 1's medium spot. Later, a car that would have used that spot has to go up to floor 2 instead.
SmallestSpotFirst protects the big spots. LowestFloorFirst saves the walk. Floor 1 has no small spot free, and floor 2 does. SmallestSpotFirst sends the motorcycle up to floor 2's small spot, keeping floor 1's medium spot for a car. LowestFloorFirst parks it in floor 1's medium spot. Later, a car that would have used that spot has to go up to floor 2 instead.

Neither rule is right in general. A mall might want LowestFloorFirst because shoppers hate ramps. An airport with few large spots might want SmallestSpotFirst. This is a business choice, which is why it sits behind an interface and the lot is given one when it is created.

Decision

Is an interface worth it for one rule?

Write the loop inside ParkingLot

This means fewer files, and it is fine if the rule never changes. But the first follow-up in most interviews is "what if we want to fill the lowest floor first?" or "fill the top floor first, so the ground floor stays free for short stays". Each one would mean editing ParkingLot, which also holds the ticket and payment logic.

SpotAllocationStrategy, with two implementationsOur pick

A new rule that needs only the floors and the vehicle type is a new class, and ParkingLot does not change. We wrote two implementations, so the interface is proven by real use rather than added "just in case".

Parking a vehicle

With the floors and the strategy in place, parking is short:

lot/ParkingLot.javalines 52–59 of 118
    public Ticket park(Vehicle vehicle) {        ParkingSpot spot = allocation.allocate(floors, vehicle.type())                .orElseThrow(() -> new LotFullException(vehicle.type()));        Ticket ticket = new Ticket(nextTicketId(), vehicle, spot, clock.instant());        activeTickets.put(ticket.id(), ticket);        announce(spot);        return ticket;    }

park asks the strategy for a spot, or turns the vehicle away with a LotFullException. It writes a ticket with a new id, the vehicle, the spot and the current time. Then it stores the ticket, tells the display boards, and returns the ticket to the gate, which prints it for the driver.

The ticket is the only record of who is in which spot. The active tickets live in a ConcurrentHashMap, which is safe to read and change from many threads at once. Ticket ids come from an AtomicLong, so two gates never print the same number:

lot/ParkingLot.javalines 26–50 of 118
public class ParkingLot {    private static final System.Logger LOG = System.getLogger(ParkingLot.class.getName());     private final List<ParkingFloor> floors;    private final Map<Integer, ParkingFloor> floorsByNumber = new HashMap<>();    private final SpotAllocationStrategy allocation;    private final PricingStrategy pricing;    private final PaymentProcessor payments;    private final Clock clock;     private final Map<String, Ticket> activeTickets = new ConcurrentHashMap<>();    private final AtomicLong ticketCounter = new AtomicLong();    private final List<AvailabilityListener> listeners = new CopyOnWriteArrayList<>();     public ParkingLot(List<ParkingFloor> floors, SpotAllocationStrategy allocation,                      PricingStrategy pricing, PaymentProcessor payments, Clock clock) {        this.floors = List.copyOf(floors);        for (ParkingFloor floor : this.floors) {            floorsByNumber.put(floor.number(), floor);        }        this.allocation = allocation;        this.pricing = pricing;        this.payments = payments;        this.clock = clock;    }

The constructor takes every collaborator as a parameter: the floors, both strategies, the payment processor and a Clock. ParkingLot never creates any of them itself. This is what lets the demo use a fake card reader and a clock it can move forward, and it is what lets a test do the same.

Leaving and paying

Leaving is where most designs have a hidden bug. Four things happen: find the ticket, calculate the fee, charge the card, free the spot. The order matters, and so does what happens when one step fails.

lot/ParkingLot.javalines 61–88 of 118
    public Receipt leave(String ticketId) {        // Removing the ticket claims it, so a second exit with the same ticket finds nothing.        Ticket ticket = activeTickets.remove(ticketId);        if (ticket == null) {            throw new TicketNotFoundException(ticketId);        }         Instant exitTime = clock.instant();        int fee;        boolean paid;        try {            fee = pricing.feeFor(ticket, exitTime);            paid = payments.charge(ticket.id(), fee);        } catch (RuntimeException e) {            // The car is still inside, so its ticket must stay active.            activeTickets.put(ticket.id(), ticket);            throw e;        }        if (!paid) {            activeTickets.put(ticket.id(), ticket);            throw new PaymentFailedException(ticket.id(), fee);        }         ParkingSpot spot = ticket.spot();        floorsByNumber.get(spot.floor()).releaseSpot(spot);        announce(spot);        return new Receipt(ticket, exitTime, fee);    }

Line by line:

  1. Claim the ticket by removing it from the map (line 63). remove is atomic, so if the same ticket is used at two exits at the same moment, only one of them gets it back. The other gets null and a TicketNotFoundException. This is how "each ticket can be used to leave exactly once" holds, with no extra lock.
  2. Calculate the fee with the pricing strategy.
  3. Charge the card. If the card is declined, the ticket goes back into the map. If the pricing or payment code throws an exception, the catch block puts it back too, then lets the exception through. The car has not left, so its ticket must stay active, or the driver could never leave.
  4. Only now free the spot (line 85), and tell the display boards.

This code cannot settle one case on its own. When charge throws on a timeout, nobody knows whether the card was charged. Putting the ticket back is still right, because the car is still inside, but a retry could charge the driver twice. The fix belongs in the payment system: it should treat the ticket id as an idempotency key, so a second charge for the same ticket returns the first result instead of charging again. That is why charge takes the ticket id at all.

Leaving, with a declined card
The exit claims the ticket by removing it from the active map, then calculates the fee and charges the card. If the card is declined, or pricing or the charge throws, the ticket goes back into the map and the barrier stays down. The driver can try another card. Only a successful charge leads to the spot going back on its floor's free list and a receipt being printed.The exit claims the ticket by removing it from the active map, then calculates the fee and charges the card. If the card is declined, or pricing or the charge throws, the ticket goes back into the map and the barrier stays down. The driver can try another card. Only a successful charge leads to the spot going back on its floor's free list and a receipt being printed.
The spot is freed only after money has been taken. The exit claims the ticket by removing it from the active map, then calculates the fee and charges the card. If the card is declined, or pricing or the charge throws, the ticket goes back into the map and the barrier stays down. The driver can try another card. Only a successful charge leads to the spot going back on its floor's free list and a receipt being printed.
Decision

When does the spot become free?

As soon as the driver reaches the exit

It feels natural, since the car is leaving. But if the card is declined, the car is still physically in the spot, and the lot has already given that spot to someone else. Two cars end up with one spot.

Only after the payment succeedsOur pick

The spot follows the money. A declined card leaves everything as it was, and the driver can try again. The cost is that while a payment is in progress, the ticket is out of the map, so "is ticket T-3 active?" briefly says no. That is fine here, because nothing else asks.

Calculating the fee

PricingStrategy has one method, feeFor(ticket, exitTime). The hourly version charges every started hour in full, with one hour as the minimum:

pricing/HourlyPricing.javalines 11–35 of 35
public class HourlyPricing implements PricingStrategy {    private final Map<VehicleType, Integer> hourlyRates;     public HourlyPricing(Map<VehicleType, Integer> hourlyRates) {        for (VehicleType type : VehicleType.values()) {            if (!hourlyRates.containsKey(type)) {                throw new IllegalArgumentException("No hourly rate for " + type);            }        }        this.hourlyRates = new EnumMap<>(hourlyRates);    }     @Override    public int feeFor(Ticket ticket, Instant exitTime) {        Duration parked = Duration.between(ticket.entryTime(), exitTime);        // Every started hour is charged as a full hour, and the first hour is always charged.        long hours = parked.toHours();        if (parked.minusHours(hours).isPositive()) {            hours++;        }        long billedHours = Math.max(1, hours);        int rate = hourlyRates.get(ticket.vehicle().type());        return Math.toIntExact(billedHours * rate);    }}

Parking for 2 hours 10 minutes is 3 started hours, so a car at $5 an hour pays $15. The constructor refuses a rate table that is missing a vehicle type, so a missing rate is found when the lot starts, not when a truck tries to leave.

Money is a whole number of dollars in an int. Never use double for money, because 0.1 + 0.2 is not exactly 0.3 in floating point. If the lot charged in cents, we would store cents in a long.

Decision

Where does the current time come from?

Instant.now() wherever it is needed

This is simple, but a fee test would have to wait two real hours, or fake the system clock some other way. Any code that reads the time on its own cannot be tested for time-based rules.

A java.time.Clock passed into ParkingLotOur pick

The lot reads the time only through clock.instant(). Production passes Clock.systemUTC(). The demo passes a ManualClock and moves it forward 130 minutes in one line. Pricing never reads the clock at all: it is given the exit time, so it is a plain function of its inputs.

Two gates, one last spot

This is the part interviewers push on most. Two cars arrive at two entry gates at the same moment, and one medium spot is left. Both gates call park() on two threads.

Two gates race for the last spot
On the left, there is no lock. Gate A reads F1-07 as the first free spot, and before it removes it, gate B reads the same spot. Both remove it and both print a ticket for F1-07. On the right, takeSpot is synchronized, so gate B waits until gate A has finished. B then finds the list empty, and that driver is turned away or sent to another floor.On the left, there is no lock. Gate A reads F1-07 as the first free spot, and before it removes it, gate B reads the same spot. Both remove it and both print a ticket for F1-07. On the right, takeSpot is synchronized, so gate B waits until gate A has finished. B then finds the list empty, and that driver is turned away or sent to another floor.
Without a lock, both gates can read the same free spot before either removes it. On the left, there is no lock. Gate A reads F1-07 as the first free spot, and before it removes it, gate B reads the same spot. Both remove it and both print a ticket for F1-07. On the right, takeSpot is synchronized, so gate B waits until gate A has finished. B then finds the list empty, and that driver is turned away or sent to another floor.

Our design makes the race impossible in one place: ParkingFloor.takeSpot is synchronized, so reading the first free spot and removing it happen as one step. The rest needs no locks. Ticket ids come from an AtomicLong, and the ticket map is a ConcurrentHashMap.

The project includes a check, demo/RaceCheck.java. It sends 1,000 cars at a floor with 100 spots through 16 threads, which a latch releases together, and counts how many spots were given out twice:

$ java demo.RaceCheck
parked 100, turned away 900, spots given twice 0

Exactly 100 cars parked and no spot went to two cars. We also ran the same check with synchronized removed from ParkingFloor. Every run gave a few spots to two cars, and the lot "parked" more than 100 cars in 100 spots. The exact numbers change from run to run and from machine to machine. The bug is real, and it never shows up when testing with one car at a time.

Decision

Where do the locks go?

One lock on the whole ParkingLot

Make park and leave synchronized. It is correct and easy to explain. Every gate waits for every other gate, but a parking lot handles a car every few seconds per gate, so the waiting would never be noticed. In an interview, this is a perfectly good answer if you say why it is enough.

A lock per floor, on the free-spot listsOur pick

The free lists are the only shared state that needs a multi-step change, and each floor owns its own lists, so each floor guards them. Each lock is held only for one pollFirst(), so gates wait for each other very briefly. Both of our rules start every gate at floor 1, so gates do queue on that floor's lock for a moment. A rule that starts gates on different floors would let them work without meeting at all. The lock sits next to the data it protects, which makes it hard to forget. The payment call also happens outside any lock, so a slow card reader at one exit does not hold up the entry gates.

Keeping the display boards current

The entrance boards show free spots per floor and size. The lot should not know how many boards there are or how they draw themselves, so the boards subscribe to changes.

display/AvailabilityListener.javalines 5–7 of 7
public interface AvailabilityListener {    void onAvailabilityChanged(int floor, SpotSize size, int freeSpots);}
lot/ParkingLot.javalines 90–113 of 118
    public void addListener(AvailabilityListener listener) {        listeners.add(Objects.requireNonNull(listener, "listener"));        for (ParkingFloor floor : floors) {            for (SpotSize size : SpotSize.values()) {                notifyQuietly(listener, floor.number(), size, floor.freeSpots(size));            }        }    }     private void announce(ParkingSpot spot) {        int freeSpots = floorsByNumber.get(spot.floor()).freeSpots(spot.size());        for (AvailabilityListener listener : listeners) {            notifyQuietly(listener, spot.floor(), spot.size(), freeSpots);        }    }     // A broken display must not stop a car from parking or leaving, or stop the other displays.    private void notifyQuietly(AvailabilityListener listener, int floor, SpotSize size, int freeSpots) {        try {            listener.onAvailabilityChanged(floor, size, freeSpots);        } catch (RuntimeException e) {            LOG.log(System.Logger.Level.WARNING, "Display update failed", e);        }    }

Look at addListener. A board that subscribes is immediately told the current counts for every floor and size. Without this, a board added at noon would show nothing until the next car came or went.

Every call to a board goes through notifyQuietly. A display is outside code: it can lose power, fail a network call or have a bug. If one throws, the lot logs a warning and carries on. Without this, a broken board would throw out of park after the spot was taken and the ticket stored, so the driver would never get the ticket, and the boards after it in the list would miss the change. The Observer pattern page covers this and the other traps of a listener list.

One thing to know about announce: when two gates change the same count at almost the same time, the two announcements can reach the board in the opposite order. The board keeps whichever value arrived last, so it can show a wrong count until the next change on that floor and size, which may be a while. For a board that drivers glance at, this is usually acceptable. If it is not, there are two fixes. The floor can attach a version number that goes up with every change, and the board ignores any update older than the one it has. Or the board can ignore the values in the message and read freeSpots() itself when told something changed.

The final design

ParkingLot is the core. It owns the floors and the active tickets, and it reaches the rules, the payment system and the display boards only through interfaces. It reads the time from a Clock it is given.

The finished design
This figure shows the classes from the class diagram without their fields. ParkingLot owns the floors and the active tickets, and uses four interfaces and a Clock, which is grey because it comes from java.time. Amber badges 1 to 7 match the rows of the table below: 1 and 5 on ParkingLot, 2 on VehicleType, 3 and 7 on ParkingFloor, 4 on SpotAllocationStrategy and 6 on Clock. Purple tags mark the two Strategy interfaces and the Observer interface.This figure shows the classes from the class diagram without their fields. ParkingLot owns the floors and the active tickets, and uses four interfaces and a Clock, which is grey because it comes from java.time. Amber badges 1 to 7 match the rows of the table below: 1 and 5 on ParkingLot, 2 on VehicleType, 3 and 7 on ParkingFloor, 4 on SpotAllocationStrategy and 6 on Clock. Purple tags mark the two Strategy interfaces and the Observer interface.
Each amber badge marks where one decision landed. The purple tags name the patterns. This figure shows the classes from the class diagram without their fields. ParkingLot owns the floors and the active tickets, and uses four interfaces and a Clock, which is grey because it comes from java.time. Amber badges 1 to 7 match the rows of the table below: 1 and 5 on ParkingLot, 2 on VehicleType, 3 and 7 on ParkingFloor, 4 on SpotAllocationStrategy and 6 on Clock. Purple tags mark the two Strategy interfaces and the Observer interface.
S.No.The questionWhat we choseWhy
1Should a gate be a class?No gate classes. A gate is just a caller of ParkingLotA gate has no behaviour of its own.
2Car, Truck and Motorcycle subclasses, or one enum?One Vehicle record with a VehicleType enumThe type is data, so it is a field.
3Where does a spot's free or taken status live?Free-spot lists on the floor, and nothing on the spotThere is one source of truth.
4Is an interface worth it for one rule?SpotAllocationStrategy, with two implementationsChanging the rule means passing a different object, not editing ParkingLot.
5When does the spot become free?Only after the payment succeedsA declined card leaves everything as it was.
6Where does the current time come from?A java.time.Clock passed into ParkingLotTests can move time forward instead of waiting.
7Where do the locks go?A lock per floor, on the free-spot listsOf the shared state, only the free lists need a multi-step change.

Here is the exit of ticket T-1 from the demo, step by step:

  1. The exit gate calls ParkingLot.leave("T-1"), and activeTickets.remove claims the ticket first. The removal is atomic, so a second exit with the same ticket finds nothing and gets a TicketNotFoundException, with no lock taken.
  2. leave reads the exit time from clock.instant() and passes it to PricingStrategy.feeFor, which calculates the fee. Pricing never reads the clock itself, so a test sets the fee by moving the clock.
  3. PaymentProcessor.charge sends the fee to the payment system. This is the outside call, and leave holds no lock while it waits, so a slow bank at one exit never blocks the entry gates. If the card is declined or the call throws, the ticket goes back into the map.
  4. ParkingFloor.releaseSpot runs only after the charge succeeds, so a declined card leaves the spot taken. It is synchronized, and the floor's lock covers only the one addLast on the free list.
  5. announce reads the new count and tells each AvailabilityListener, and a board that throws is only logged. Then leave returns a Receipt with the fee.

Parking is the one entry path. park asks SpotAllocationStrategy.allocate for a spot, the strategy takes it with takeSpot under the floor's lock, and park writes and stores the ticket only after that.

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 interface, an enum or a record.

lotParkingLot.java
package lot; import java.time.Clock;import java.time.Instant;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Objects;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.CopyOnWriteArrayList;import java.util.concurrent.atomic.AtomicLong; import allocation.SpotAllocationStrategy;import display.AvailabilityListener;import exception.LotFullException;import exception.PaymentFailedException;import exception.TicketNotFoundException;import payment.PaymentProcessor;import pricing.PricingStrategy;import spot.ParkingSpot;import spot.SpotSize;import ticket.Receipt;import ticket.Ticket;import vehicle.Vehicle; public class ParkingLot {    private static final System.Logger LOG = System.getLogger(ParkingLot.class.getName());     private final List<ParkingFloor> floors;    private final Map<Integer, ParkingFloor> floorsByNumber = new HashMap<>();    private final SpotAllocationStrategy allocation;    private final PricingStrategy pricing;    private final PaymentProcessor payments;    private final Clock clock;     private final Map<String, Ticket> activeTickets = new ConcurrentHashMap<>();    private final AtomicLong ticketCounter = new AtomicLong();    private final List<AvailabilityListener> listeners = new CopyOnWriteArrayList<>();     public ParkingLot(List<ParkingFloor> floors, SpotAllocationStrategy allocation,                      PricingStrategy pricing, PaymentProcessor payments, Clock clock) {        this.floors = List.copyOf(floors);        for (ParkingFloor floor : this.floors) {            floorsByNumber.put(floor.number(), floor);        }        this.allocation = allocation;        this.pricing = pricing;        this.payments = payments;        this.clock = clock;    }     public Ticket park(Vehicle vehicle) {        ParkingSpot spot = allocation.allocate(floors, vehicle.type())                .orElseThrow(() -> new LotFullException(vehicle.type()));        Ticket ticket = new Ticket(nextTicketId(), vehicle, spot, clock.instant());        activeTickets.put(ticket.id(), ticket);        announce(spot);        return ticket;    }     public Receipt leave(String ticketId) {        // Removing the ticket claims it, so a second exit with the same ticket finds nothing.        Ticket ticket = activeTickets.remove(ticketId);        if (ticket == null) {            throw new TicketNotFoundException(ticketId);        }         Instant exitTime = clock.instant();        int fee;        boolean paid;        try {            fee = pricing.feeFor(ticket, exitTime);            paid = payments.charge(ticket.id(), fee);        } catch (RuntimeException e) {            // The car is still inside, so its ticket must stay active.            activeTickets.put(ticket.id(), ticket);            throw e;        }        if (!paid) {            activeTickets.put(ticket.id(), ticket);            throw new PaymentFailedException(ticket.id(), fee);        }         ParkingSpot spot = ticket.spot();        floorsByNumber.get(spot.floor()).releaseSpot(spot);        announce(spot);        return new Receipt(ticket, exitTime, fee);    }     public void addListener(AvailabilityListener listener) {        listeners.add(Objects.requireNonNull(listener, "listener"));        for (ParkingFloor floor : floors) {            for (SpotSize size : SpotSize.values()) {                notifyQuietly(listener, floor.number(), size, floor.freeSpots(size));            }        }    }     private void announce(ParkingSpot spot) {        int freeSpots = floorsByNumber.get(spot.floor()).freeSpots(spot.size());        for (AvailabilityListener listener : listeners) {            notifyQuietly(listener, spot.floor(), spot.size(), freeSpots);        }    }     // A broken display must not stop a car from parking or leaving, or stop the other displays.    private void notifyQuietly(AvailabilityListener listener, int floor, SpotSize size, int freeSpots) {        try {            listener.onAvailabilityChanged(floor, size, freeSpots);        } catch (RuntimeException e) {            LOG.log(System.Logger.Level.WARNING, "Display update failed", e);        }    }     private String nextTicketId() {        return "T-" + ticketCounter.incrementAndGet();    }}
Click a class name in the code to open its fileJava · 118 lines · 597 in the project

demo/Main.java runs a small two-floor lot through a morning. Six vehicles arrive and the second truck is turned away. The first car leaves after 2 hours 10 minutes. Then the first truck tries to leave with a card that is declined, and pays on the second try:

$ java demo.Main
KA-01-AB-1234 (CAR) -> F1-02, ticket T-1
KA-05-XY-0001 (MOTORCYCLE) -> F1-01, ticket T-2
KA-51-TR-7777 (TRUCK) -> F1-04, ticket T-3
KA-03-CD-4321 (CAR) -> F1-03, ticket T-4
KA-02-EF-1111 (CAR) -> F2-03, ticket T-5
KA-52-TR-8888 (TRUCK) turned away: No free spot for a TRUCK
Floor 1:  SMALL 0  MEDIUM 0  LARGE 0
Floor 2:  SMALL 2  MEDIUM 1  LARGE 0

KA-01-AB-1234 left after 2h 10m and paid $15
Second exit with the same ticket: No active ticket T-1
Floor 1:  SMALL 0  MEDIUM 1  LARGE 0
Floor 2:  SMALL 2  MEDIUM 1  LARGE 0

Payment of $30 for T-3 failed. The barrier stays down
Floor 1:  SMALL 0  MEDIUM 1  LARGE 0
Floor 2:  SMALL 2  MEDIUM 1  LARGE 0
Second try: paid $30, spot F1-04 is free again
Floor 1:  SMALL 0  MEDIUM 1  LARGE 1
Floor 2:  SMALL 2  MEDIUM 1  LARGE 0

Notice three things in the output. The motorcycle took F1-01, floor 1's only small spot, and left the medium spots for cars. Using ticket T-1 a second time fails. And after the declined card, the board still shows floor 1 with no large spot free. The spot frees up only after the second payment goes through.

Follow-up questions

After the core design, interviewers usually add a requirement to see how the design bends. A good design absorbs most of them in one or two classes. For each one, say which class changes and which do not.

The interviewer asksWhat changesWhat does not
"Add electric vehicle spots with chargers."A new SpotSize value such as EV, or a separate charger list on the floor. An EV-aware allocation strategy.ParkingLot, tickets, payment.
"Night parking is a flat $10."A new NightFlatPricing, or a pricing class that picks a rule by entry time.Everything else.
"Charge by the minute after the first hour."A new PricingStrategy.Everything else.
"Keep the ground floor for disabled drivers."Add accessible to ParkingSpot and Vehicle. The floor keeps accessible spots in their own free list. allocate takes the whole Vehicle instead of its type, so park passes the vehicle.Pricing, payment, tickets.
"Stop a car from entering twice."A map from licence plate to active ticket. park claims the plate with putIfAbsent before taking a spot, and leave removes the plate. If no spot is free, park releases the plate claim.Floors, allocation, pricing.
"Let people book a spot in advance."A reservation holds a spot taken from the free list until its start time, then turns into a ticket or expires. A small new Reservation class and a scheduler.Floors and allocation work as they are.
"Drivers lose their tickets."The plate map from the row above finds the ticket. Usually a fixed lost-ticket fee.Pricing for normal exits.
"Several lots across the city."One ParkingLot per site. A thin service above them that picks a lot.Nothing inside a lot.
"Cameras read the number plate instead of a ticket."Entry looks up the plate, exit finds the ticket by plate. The plate map from the lost-ticket answer.Pricing, payment, floors.

In most rows the change lands in a strategy, a new record field or a new class beside the core, and ParkingLot and ParkingFloor change little or not at all. When you answer a follow-up, say which classes change and which do not.

What the interviewer looks for

Mid-level

A mid-level candidate shows a clear set of classes with sensible names and relationships, a working park and leave, enums for vehicle and spot types instead of strings, and a pricing rule that is correct for the obvious cases. They mention that several gates means some locking is needed, even if they put the lock in a less than ideal place.

Senior

A senior candidate shows everything above and gives the reasons. They explain why the free status lives on the floor and not the spot, and why pricing and allocation are interfaces. They say where the lock goes and why that is enough. They walk through the order of steps in leave, and what happens on a declined payment. They pass in a clock so tests can control time. They also say when a simpler choice would do, for example one lock on the whole lot.

Staff+

A staff candidate leads the conversation through the trade-offs without being asked. They point out what the design deliberately does not handle: a crash after the charge and before the spot is freed, two announcements arriving out of order, a slow payment call. They can say how each would be handled if this became a real service, for example making the charge idempotent with the ticket id as the key, so a retried exit is never charged twice.

Common mistakes

  • A subclass for every vehicle type with nothing inside it. Types that only differ in data belong in an enum.
  • An isFree flag on each spot, checked and then set in two steps. Two gates can both see the spot as free. Taking a spot must be a single step under one lock.
  • Freeing the spot before payment succeeds. A declined card then leaves a car in a spot the lot thinks is empty.
  • Fee logic inside ParkingLot. The first follow-up about weekend or night rates means editing the class that also handles locking and tickets.
  • double for money, and Instant.now() scattered through the code. Both make the pricing hard to get right and impossible to test.
  • A ParkingLot singleton. It feels natural because there is one lot, but it hides the lot's collaborators and makes tests share state. Create one instance at startup and pass it to whatever needs it.
  • Drawing twenty classes before agreeing on requirements. Ask the questions in the first table first. Half the classes depend on the answers.

Summary

  • Ask before designing. The number of gates, the fee rule and whether small vehicles may use big spots each change the code.
  • Keep only the nouns that have a job. A gate is a caller, not a class.
  • Use records for data that never changes and enums for fixed sets of types.
  • Put "is this spot free?" in one place, the floor's free lists, and take a spot in one locked step.
  • Put the rules that will change, spot choice and pricing, behind interfaces.
  • On exit, claim the ticket, charge, and only then free the spot. Put the ticket back if pricing or the charge fails for any reason.
  • Pass the clock in, so time-based rules can be tested.

Spot a mistake, or something unclear? . Or get in touch.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.