AlgoViz

Design a parking lot

medium 90 min

Model 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 askFirst sentenceThen
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

ToolUseChoose it when
synchronizedMutual exclusionSeveral fields must change together
ReentrantLockThe same, with time limits and fairnessYou must give up waiting
SemaphoreN permitsN equal things, and callers may wait
ConcurrentHashMapSafe single operations on a mapOne fact for each key
ConcurrentLinkedDequeAtomic take from a queueFree lists
AtomicLongCounter without a lockIds
AtomicReference, compare and setChange if still the sameOne space, one owner
volatileOthers see the writeA flag, or the safe Singleton. It does not make check then act safe
CopyOnWriteArrayListRead often, change rarelyListeners

Failure

Beyond one process

What failsWhat you say
Power at the gateBarriers open by hand, tickets are on disk, free is rebuilt
The network to the databaseEach gate has a lease of a few spaces; the rest waits
The payment providerPay later by plate, or open and write it down; a business decision
The databaseEnter refuses, leave lets people out: never trap a car