Design a parking lot
medium 90 minModel a car park with several levels as classes: vehicles, spaces of different sizes, tickets and a replaceable price rule.
Watch lesson4:48
Deep dives
Compare the options before you open them, then say which you would pick.
Dig
Where they go next, and your first sentence
| They ask | First sentence | Then |
|---|---|---|
| Two gates, one space | "Taking must be the check." | Two cars, one space |
| Faster search | "Which question: any, nearest, or a run?" | Finding a space fast |
| More gates | "Let me do the sum first." | Many gates and floors |
| Night rates | "Length in UTC, rate in local time." | Pricing that changes |
| The card times out | "Same key, same amount, again." | Payment and lost tickets |
| Booking | "Capacity, not a numbered space." | Reservations and expiry |
| Electric | "From a size to a need." | Extending it |
| How do you test it | "I force the bad order." | Testing the races |
Toolbox
Concurrency tools, one line each
| Tool | Use | Choose it when |
|---|---|---|
synchronized | Mutual exclusion | Several fields must change together |
ReentrantLock | The same, with time limits and fairness | You must give up waiting |
Semaphore | N permits | N equal things, and callers may wait |
ConcurrentHashMap | Safe single operations on a map | One fact for each key |
ConcurrentLinkedDeque | Atomic take from a queue | Free lists |
AtomicLong | Counter without a lock | Ids |
AtomicReference, compare and set | Change if still the same | One space, one owner |
volatile | Others see the write | A flag, or the safe Singleton. It does not make check then act safe |
CopyOnWriteArrayList | Read often, change rarely | Listeners |
Failure
Beyond one process
| What fails | What you say |
|---|---|
| Power at the gate | Barriers open by hand, tickets are on disk, free is rebuilt |
| The network to the database | Each gate has a lease of a few spaces; the rest waits |
| The payment provider | Pay later by plate, or open and write it down; a business decision |
| The database | Enter refuses, leave lets people out: never trap a car |