"Design a library management system" sounds like a list of books with a borrow button. It is easy to draw a Library, a Book, a Member and a Librarian, add borrow() and return(), and stop there. That leaves out the hard parts of the question: a book with several copies, a member at their limit, a fine that the library wants to change, and three people waiting for the one copy that just came back.
The interviewer wants to see how you turn those rules into classes with clear jobs, and how you keep them correct when two desks act on the same book at the same moment. 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.
Ask before you design
The question is vague on purpose. Each question below changes the code, and the right-hand column says how.
| Question | What we assume | What it changes |
|---|---|---|
| One branch or several? | One branch | One Library object |
| Can the library own several copies of a book? | Yes, each with its own barcode | A Book for the title and a BookCopy for each barcode |
| How many books can a member have out? | 3 on a standard card, 5 on a premium card | A MembershipPlan enum with a limit |
| How long is a loan? | 14 days | A due time on every loan, read from a clock we pass in |
| What happens when a book comes back late? | $5 for each day late, at most $200 for one return. The rule may change | A fine rule behind an interface, and money in cents |
| Can a member who owes fines borrow? | Yes, up to $100 owed. Above that, not until they pay | A check before every loan |
| What if every copy is out? | The member joins a queue for that book, first come first served | A waiting list per book |
| How long is a returned copy kept for the next person? | 3 days. Then it passes to the next person in the queue | A pickup deadline, and something that checks it |
| One desk or several? | Several desks and an app, all at once | The code must be safe when called from many threads |
"What if every copy is out?" changes the most. Without a queue, a returned copy goes back on the shelf and the fastest walk-in gets it. With a queue, a returned copy belongs to one person for a while, and the design has to track who, until when, and what happens when they do not come.
Requirements
Functional:
- A member borrows a book if a copy is free, they have fewer books out than their plan allows, and they owe $100 or less. Each loan is due 14 days later. A refused request takes no slot and no copy.
- A member hands a copy back at any desk. A late return adds a fine, calculated by the fine rule, to what the member owes.
- A member pays towards their fines, but never more than they owe.
- If no copy is free, a member can join that book's queue. Members are served in the order they joined.
- A returned copy goes to the first member waiting. It is kept for them for 3 days, and they are told. If they do not collect it in time, it passes to the next member, or back to the shelf.
- The desk can say where any copy is: on the shelf, on loan, or kept for someone.
Out of scope: searching by title or author, renewing a loan, cancelling a hold, booking a book for a date, lost or damaged copies, and several branches. We come back to each of these at the end.
Everything lives in memory, as is normal for a low-level design interview. Saving loans so they survive a restart is a storage question for a separate discussion.
What the code itself must handle:
- Many desks at once. Desks and the app call the library from several threads together.
- A rule that changes. The library will change how fines work. That should not mean editing the core classes.
- Time. Due dates, fines and pickup deadlines all depend on the time, so a test must be able to control the clock.
- An outside system that fails. The text message (SMS) service can be slow or down. A failed message must not undo a return.
Finding the classes
We start by picking out the nouns in the requirements. Most become classes, records or enums. Some do not, and dropping them is part of the design.
The fine is the noun worth arguing about.
Should a fine be its own class?
A Fine object for each late return
Each fine would remember its loan, its amount and whether it was paid. That is a full history, which a real library might want for its accounts. But the only question this design asks is "how much does this member owe?", and a list of fines answers it by adding them up each time. Paying $100 towards three fines also raises a question nobody asked: which fine does it pay?
A balance in cents on the member's accountOur pick
MemberAccount keeps one number, finesOwedCents. A late return adds to it, a payment takes from it, and the borrowing check reads it. Nothing has to be added up, so the check is one comparison. If the library later wants a history of fines, a list of records can sit beside the balance without changing how borrowing works.
Data or behaviour?
Some types only carry data and never change once created: a book, a copy, a member, a loan. In Java these are records. A record is a class whose fields are fixed when it is created, and Java writes its equals, hashCode and toString for it. Each record here checks its own fields when it is built, so a loan that is due before it starts cannot exist:
public record Loan(BookCopy copy, String memberId, Instant borrowedAt, Instant dueAt) { public Loan { Objects.requireNonNull(copy, "copy"); Objects.requireNonNull(memberId, "memberId"); Objects.requireNonNull(borrowedAt, "borrowedAt"); Objects.requireNonNull(dueAt, "dueAt"); if (!dueAt.isAfter(borrowedAt)) { throw new IllegalArgumentException("a loan must be due after it starts"); } }}The class diagram
The classes fall into three groups:
- Data:
Book,BookCopy,Member,MembershipPlan,Loan,KeptCopy,HoldReady,CopyStatusandLibraryRules, which are records and enums, and two small result classes,BorrowResultandReturnResult. - The core:
Library,BookShelfandMemberAccount. These hold the state that changes (who has what, who is waiting, who owes what) and keep it correct under many threads. - Rules and outside systems:
FinePolicyandHoldNotifier. Both are interfaces, so the core never depends on a particular fine rule or SMS service.
Building it
A book and its copies
A library may own five copies of a popular book. Each copy has a barcode, and the desk scans that barcode when the copy comes back.
public record BookCopy(String id, String isbn) { public BookCopy { Objects.requireNonNull(id, "id"); Objects.requireNonNull(isbn, "isbn"); if (id.isBlank() || isbn.isBlank()) { throw new IllegalArgumentException("a copy needs an id and an ISBN"); } }}One class for a book, or a book and its copies?
One Book with a count of copies
A Book with available = 3 is simple. But a return names a physical copy, and a count cannot say which copy came back or who had it. A copy kept for one member also needs a name, so that the desk can find it on the hold shelf.
Book for the title, BookCopy for each barcodeOur pick
Book holds what all copies share: the ISBN (International Standard Book Number), the title and the author. BookCopy is one physical copy with its own id. A loan points at a copy, so "who has copy MD-1?" has one answer. The two records stay small, and neither knows where its copy is right now.
Where a copy is
A copy is in one of three places: on the shelf, out on loan, or kept at the desk for someone. The obvious design puts a status field on each copy. We do something else: each book gets a BookShelf, which keeps every copy of that book in exactly one of three collections, and the queue of members in a fourth.
final class BookShelf { private final Object lock = new Object(); private final Book book; private final Clock clock; private final Duration loanPeriod; private final Duration pickupWindow; private final Deque<BookCopy> onShelf = new ArrayDeque<>(); private final Map<String, Loan> loans = new LinkedHashMap<>(); private final Deque<String> waiting = new ArrayDeque<>(); private final Map<String, KeptCopy> kept = new LinkedHashMap<>();onShelfholds the copies anyone may borrow.loansmaps a copy id to its loan.waitingis the queue of member ids, oldest first.keptmaps a member id to the copy kept for them and its deadline.
A copy moves between onShelf, loans and kept, and the move happens under that book's own lock. The desk's question "where is MD-1?" first passes on any kept copy whose deadline has been reached (line 140), which comes up later, and then reads the collections. A barcode in none of them gets an empty answer rather than an exception:
/** Where the copy is, or empty if it is in none of this book's lists. */ Optional<CopyStatus> statusOf(String copyId, List<HoldReady> notices) { synchronized (lock) { Instant now = clock.instant(); expireKept(now, now.plus(pickupWindow), notices); if (loans.containsKey(copyId)) { return Optional.of(CopyStatus.ON_LOAN); } for (KeptCopy keptCopy : kept.values()) { if (keptCopy.copy().id().equals(copyId)) { return Optional.of(CopyStatus.KEPT_FOR_HOLD); } } for (BookCopy copy : onShelf) { if (copy.id().equals(copyId)) { return Optional.of(CopyStatus.ON_SHELF); } } return Optional.empty(); } }Where does a copy's status live?
A status field on each BookCopy
This is easy to picture. But lending a copy would mean changing the copy and the loans map together, and the two can disagree if one step fails or another thread runs between them. Finding a free copy would also mean scanning every copy for the right status.
In its book's lists, and nothing on the copyOur pick
A copy is on the shelf if and only if it is in onShelf, and the same holds for the other collections. Lending is one pollFirst() and one put under one lock. BookCopy stays an unchangeable record, and CopyStatus is worked out when someone asks. The cost is that statusOf searches the lists, which is fine for the handful of copies one book has.
A member's limit and fines
Each member has a MemberAccount that counts their books out and their fines owed. It has its own lock: every method is synchronized.
/** Takes one of the member's loan slots, or says why not. Empty means the slot is taken. */ synchronized Optional<BorrowOutcome> reserveLoan(long blockAboveCents) { if (finesOwedCents > blockAboveCents) { return Optional.of(BorrowOutcome.FINES_DUE); } if (loansOut >= member.plan().borrowLimit()) { return Optional.of(BorrowOutcome.LIMIT_REACHED); } loansOut++; return Optional.empty(); }reserveLoan checks the fines first, then the limit, and then takes a slot by adding one to loansOut. It returns an empty Optional when the slot is taken, or the reason it is not. The checks and the change happen in one synchronized method, so two desks cannot both see a member at 2 of 3 and both take the third slot.
The fines check uses >, so a member who owes exactly $100 can still borrow, and one who owes $100.01 cannot. The limit comes from the member's plan: 3 for STANDARD, 5 for PREMIUM.
Borrowing a copy
A borrow touches two things: the member's slot and the copies of one book. They live behind two different locks, so the order matters.
public BorrowResult borrow(String memberId, String isbn) { Objects.requireNonNull(memberId, "memberId"); Objects.requireNonNull(isbn, "isbn"); MemberAccount account = accounts.get(memberId); if (account == null) { return BorrowResult.refused(BorrowOutcome.NO_SUCH_MEMBER); } BookShelf shelf = shelves.get(isbn); if (shelf == null) { return BorrowResult.refused(BorrowOutcome.NO_SUCH_BOOK); } Optional<BorrowOutcome> refusal = account.reserveLoan(rules.blockBorrowingAboveCents()); if (refusal.isPresent()) { return BorrowResult.refused(refusal.get()); } List<HoldReady> notices = new ArrayList<>(); BorrowResult result; try { result = shelf.lend(memberId, notices); } catch (Throwable t) { account.releaseLoan(); throw t; } finally { send(notices); } if (!result.lent()) { account.releaseLoan(); } return result; }borrow first looks up the account and the shelf. An unknown card or an unknown book is an answer, not an exception, because a person can type either one wrongly. Then it takes a slot from the account (line 102). Only after that does it ask the shelf for a copy (line 109). If the shelf has no copy, or the member already has this book, borrow gives the slot back (line 117). If the shelf throws anything at all, the catch gives the slot back and lets the same exception through. Any notices the shelf produced are sent in the finally (line 114), so a change that was made is announced even if the call then throws.
Check the member first, or the copy first?
Take a copy, then check the member
This reads naturally: find a copy, then see if the member may have it. But if the member is over their limit, the copy has to go back on the shelf. If a hold was waiting, the copy should go to that member instead, which is the return path all over again. Undoing a copy is much harder than undoing a number.
Take the member's slot first, and give it back if no copy is lentOur pick
A slot is one number on one account, so giving it back is one line. The copy is touched only once the member is allowed to have it. The cost is a short moment when the slot is counted but no copy is lent yet. A member at 2 of 3 who borrows two books at the same instant may be refused one of them even if the other book turns out to have no copy. Trying again works.
Here is the shelf's side of a borrow:
BorrowResult lend(String memberId, List<HoldReady> notices) { synchronized (lock) { // Work out every time first: if the clock cannot add, nothing has changed yet. Instant now = clock.instant(); Instant dueAt = now.plus(loanPeriod); Instant keptUntil = now.plus(pickupWindow); expireKept(now, keptUntil, notices); if (hasLoan(memberId)) { return BorrowResult.refused(BorrowOutcome.ALREADY_HAS_THIS_BOOK); } BookCopy copy; KeptCopy keptForThem = kept.remove(memberId); if (keptForThem != null) { copy = keptForThem.copy(); // The copy may have reached them during this very call: they have it now, so no message. notices.removeIf(notice -> notice.memberId().equals(memberId)); } else { copy = onShelf.pollFirst(); if (copy == null) { return BorrowResult.refused(BorrowOutcome.NO_COPY_AVAILABLE); } } Loan loan = new Loan(copy, memberId, now, dueAt); loans.put(copy.id(), loan); return BorrowResult.lent(loan); } }lend first works out the due date and a fresh pickup deadline (lines 65 and 66), before it touches any list. If the clock cannot add 14 days to the time, the call throws there and nothing has moved. Then lend passes on any copy whose pickup deadline has been reached (line 67); we come back to that. It refuses a member who already has a copy of this book. A copy kept for this member comes first (lines 72 to 76). Otherwise lend takes the first copy off the shelf (line 78). A copy kept for someone else is never in onShelf, so nobody can take it by accident. The loan is due loanPeriod after now, which is 14 days in the demo.
Handing a copy back
A return has four steps: find the loan, calculate the fine, take the copy back, and close the loan on the member's account.
public ReturnResult returnCopy(String copyId) { Objects.requireNonNull(copyId, "copyId"); String isbn = isbnOfCopy.get(copyId); if (isbn == null) { return ReturnResult.refused(ReturnOutcome.NO_SUCH_COPY); } BookShelf shelf = shelves.get(isbn); Optional<Loan> found = shelf.loanOf(copyId); if (found.isEmpty()) { return ReturnResult.refused(ReturnOutcome.NOT_ON_LOAN); } Loan loan = found.get(); long fine = finePolicy.fineFor(loan.dueAt(), clock.instant()); if (fine < 0 || fine > FinePolicy.MAX_FINE_CENTS) { throw new IllegalStateException("the fine rule returned " + fine + " cents"); } List<HoldReady> notices = new ArrayList<>(); try { if (!shelf.takeBack(loan, notices)) { return ReturnResult.refused(ReturnOutcome.NOT_ON_LOAN); } accounts.get(loan.memberId()).endLoan(fine); return ReturnResult.returned(loan, fine, keptFor(copyId, notices)); } finally { send(notices); } }- Find the loan with
loanOf(line 129). A copy that is not on loan is an answer,NOT_ON_LOAN, because two desks can scan the same copy. - Calculate the fine from the loan's due time and now (line 134). This runs before anything changes. A fine below zero or above
FinePolicy.MAX_FINE_CENTS($100,000) is a bug in the rule, soreturnCopythrows, and still nothing has changed. - Take the copy back with
takeBack(line 140). It checks, under the shelf's lock, that this exact loan is still there. If another desk ended it a moment earlier,takeBackreturns false and this desk answersNOT_ON_LOAN. It works out the pickup deadline and passes on lapsed copies before that check, so a clock that cannot add leaves the copy on loan. - Close the loan on the member's account (line 143).
endLoanfrees the slot and adds the fine. The notices go out in thefinally, whichever way the call ends.
/** Ends this exact loan. False if another desk ended it first. */ boolean takeBack(Loan loan, List<HoldReady> notices) { synchronized (lock) { Instant now = clock.instant(); Instant keptUntil = now.plus(pickupWindow); expireKept(now, keptUntil, notices); // The same loan object, not an equal one: the copy may have been lent again since. if (loans.get(loan.copy().id()) != loan) { return false; } loans.remove(loan.copy().id()); arrive(loan.copy(), keptUntil, notices); return true; } }The != on line 120 compares the loan objects themselves, not their values. If the copy had been returned and lent to the same member again at the same instant, an equal loan would be there, and a stale second scan must not end it.
When is the fine calculated?
After the copy is taken back
This feels natural: the copy is back, so now work out what is owed. But the fine rule is code that can fail. If it throws after the copy is back on the shelf or kept for someone, the member still has a loan counted and no fine, and the copy may already belong to the next person. Putting it all back is hard.
From the loan, before the copy is taken backOur pick
returnCopy reads the loan, calculates the fine, and only then changes anything. A rule that throws leaves the copy on loan and the account unchanged, and the desk can try again. The fine uses the time the desk scanned the copy, a moment before the lock is taken, which is the time the member handed it over.
Calculating the fine
The fine is the rule most likely to change. Some libraries charge from the first late day, some give a few days' grace, and some cap the fine at the price of a new copy.
public interface FinePolicy { /** No rule may charge more than $100,000 for one return. */ long MAX_FINE_CENTS = 100_000_00; /** The fine for a copy due at {@code dueAt} and returned at {@code returnedAt}. Zero when it is on time. */ long fineFor(Instant dueAt, Instant returnedAt); /** Every started 24 hours after the due time counts as one day late. */ static long daysLate(Instant dueAt, Instant returnedAt) { if (!returnedAt.isAfter(dueAt)) { return 0; } Duration late = Duration.between(dueAt, returnedAt); long days = late.toDays(); if (late.compareTo(Duration.ofDays(days)) > 0) { days++; } return days; }}daysLate counts every started 24 hours after the due time as one day, so a copy one second late is one day late. The default rule charges a fixed amount for each day, up to a cap:
public long fineFor(Instant dueAt, Instant returnedAt) { long days = FinePolicy.daysLate(dueAt, returnedAt); // Compare before multiplying, so a very late return cannot overflow. if (days > capCents / centsPerDay) { return capCents; } return days * centsPerDay; }A 30 day delay at $5 a day is $150. A 50 day delay would be $250, so the cap of $200 applies. The method compares the days with capCents / centsPerDay before it multiplies, so even a copy returned centuries late cannot overflow a long. Both rules also refuse, when they are built, a cap above FinePolicy.MAX_FINE_CENTS, so no rule we ship can produce a fine that returnCopy refuses, and a copy can always come back. Money is a whole number of cents in a long, never a double.
The second rule, GraceDaysFine, makes the first few days free:
Holds: who gets a returned copy
When no copy is free, a member joins that book's queue:
HoldOutcome placeHold(String memberId, List<HoldReady> notices) { synchronized (lock) { Instant now = clock.instant(); expireKept(now, now.plus(pickupWindow), notices); if (hasLoan(memberId)) { return HoldOutcome.ALREADY_HAS_THIS_BOOK; } if (kept.containsKey(memberId) || waiting.contains(memberId)) { return HoldOutcome.ALREADY_WAITING; } if (!onShelf.isEmpty()) { return HoldOutcome.COPY_AVAILABLE; } waiting.addLast(memberId); return HoldOutcome.PLACED; } }placeHold refuses a member who already has a copy or is already waiting, and refuses a hold while a copy sits on the shelf (line 99), because that member can borrow it. Otherwise the member joins the back of waiting.
When a copy comes back, arrive decides where it goes:
/** A copy is free: the member who has waited longest gets it kept until keptUntil, or it goes on the shelf. */ private void arrive(BookCopy copy, Instant keptUntil, List<HoldReady> notices) { String next = waiting.pollFirst(); if (next == null) { onShelf.addLast(copy); return; } kept.put(next, new KeptCopy(copy, next, keptUntil)); notices.add(new HoldReady(next, book, copy.id(), keptUntil)); }If nobody is waiting, the copy goes on the shelf. Otherwise the member who has waited longest gets it, kept until the keptUntil its caller worked out (now plus pickupWindow), and a HoldReady notice is added to the list the caller will send. Adding a new copy goes through arrive too, so a new copy of a book with a queue is kept for the first member waiting. If adding a copy fails part way, addCopy takes the barcode back off its index, so the same barcode can be added again.
A copy comes back and someone is waiting. Where does it go?
Back on the shelf, for whoever asks first
This is the simplest, and the queue becomes a list of people to phone. But a walk-in can take the copy before the first member hears about it, so the queue promises nothing.
Lend it straight to the first member waiting
The member gets a copy with no extra step. But their loan clock starts while the copy sits at the desk, they may no longer want it, and a member at their limit would be pushed over it.
Keep it for the first member waiting, until a pickup deadlineOur pick
The copy is set aside for one member for 3 days. They collect it with a normal borrow, which checks their limit and fines then. If they do not come, the copy moves on. The cost is a new kind of state, a kept copy with a deadline, which the design has to expire.
A copy nobody collects
A kept copy's deadline passes quietly. Nothing happens at that moment unless some code checks. expireKept does the checking:
/** Copies kept past their deadline pass to the next member waiting, or back to the shelf. */ private void expireKept(Instant now, Instant keptUntil, List<HoldReady> notices) { List<KeptCopy> lapsed = new ArrayList<>(); for (KeptCopy keptCopy : kept.values()) { if (!now.isBefore(keptCopy.keptUntil())) { lapsed.add(keptCopy); } } for (KeptCopy keptCopy : lapsed) { kept.remove(keptCopy.memberId()); arrive(keptCopy.copy(), keptUntil, notices); } }Every kept copy whose deadline has been reached passes on through arrive, to the next member waiting or back to the shelf. A copy is kept while the time is before its deadline, so a member who comes exactly at the deadline has lost the hold. If somebody else is waiting, the copy goes to them. If nobody is, the copy goes back on the shelf, and the same borrow then lends it like any other copy. The member whose time ran out leaves the queue. If they still want a copy, they join the back of the queue again.
expireKept runs inside the shelf's lock at the start of every desk call on that book: lend, placeHold, takeBack, addCopy, statusOf and waiting. Only loanOf skips it. A return of a copy that is not on loan stops at loanOf and changes nothing; every other return reaches takeBack, which passes lapsed copies on before its check. A nightly job also calls expireHolds, which runs it on every book:
Who passes on a copy that nobody collects?
A timer for each kept copy
A scheduled task fires at each deadline. It is exact, but it adds threads, the tests have to wait for real time, and a timer that fires while a desk is lending the same copy needs the same lock anyway.
Only a nightly job
This is simple, but a copy kept until 10 a.m. stays kept until the job runs at night. The next member waits most of a day for nothing, and a desk that asks about that book in between sees a stale answer.
Every call on that book checks first, and a nightly sweep catches the restOur pick
Any desk that asks about or changes that book sees it as it should be at that moment, because expireKept runs inside the shelf's lock first. The cost is that even a question changes state: statusOf and waitingFor take that book's lock, and can pass a copy on and send a message. The nightly sweep only matters for books nobody touched that day, so their next member is still told. The clock is passed in, so a test moves time forward and checks the deadline to the second.
One more detail is in lend. If a member's own borrow is the call that passes a lapsed copy to them, they collect it in that same call. lend then removes the notice for them (line 76), so that borrow sends no SMS about the copy it has just lent.
Telling the member
A notice needs an SMS or an email, which is outside our code. It may be slow, and it may fail.
send runs after the shelf has let go of its lock. Every shelf method collects notices in a list, and Library sends them in a finally once the shelf call has returned. If the notifier throws a runtime exception, send counts it in failedNotices and moves on to the next notice. The copy stays kept, so the member can still collect it, and the desk can check the count. Because no lock is held, a notifier that calls back into the library, for example to borrow the copy for the member, works.
When is the member told their copy is ready?
Inside each book's lock, as soon as the copy is kept
The message goes out at the exact moment the copy is kept. But a slow SMS service would then hold that book's lock, and every desk asking about that book would wait for it. A notifier that throws would also stop the return half way.
After each book's lock is released, and a failed message is countedOur pick
The lock is held only for a few changes to the lists. A slow message slows only the desk that sent it, and a failed message is counted rather than undoing the return. The cost is that a failed message is not sent again on its own. A real library would put it in a queue to retry, which is a follow-up below.
Many desks at once
Several desks and the app call the library at the same moment. Three races matter: two members borrowing the last copy, one member near their limit borrowing several books at once, and two copies coming back at once while members wait.
Each BookShelf guards all four of its collections with one lock, so reading the queue and keeping a copy happen as one step. Each MemberAccount guards its own counts. Library itself holds no lock: its maps are ConcurrentHashMaps, and it calls the shelf and the account one after the other, never one inside the other.
The project includes demo/RaceCheck.java. It runs each race many times, starting every thread in a round at the same moment. It counts the rounds that went wrong, and on a line of their own, the rounds where a desk crashed:
Last copy: 300 rounds, 8 members, 1 copy rounds where the copy went to more than one member: 0 rounds where a desk crashed: 0 Holds: 300 rounds, 4 copies returned while 4 members wait and 4 others borrow rounds with a waiting member skipped or served twice: 0 rounds where a member who was not waiting got a copy: 0 rounds where a desk crashed: 0 Limit: 2000 rounds, a member with 2 of 3 books out borrows 6 books at once rounds that went over the limit: 0 rounds where a desk crashed: 0
Every count is zero. We also ran the same check with the locks removed from BookShelf and MemberAccount. In every run, between about one in six and two in five hold rounds crashed with a ConcurrentModificationException: one desk was walking the loans or kept map while another desk changed it. In most runs a few more hold rounds went wrong without crashing, skipping a waiting member or giving a walk-in a copy. The last-copy and limit races went wrong in a few rounds of most runs, as one copy lent to two members or a fourth book on a standard card. The exact counts change from run to run. A race that shows up rarely is still a bug.
Where do the locks go?
One lock on the whole library
Library makes every public method synchronized. It is correct and easy to explain. Every desk then waits for every other desk, even when they work on different books. For a small branch that would never be noticed, and it is a fine answer in an interview if you say why it is enough.
A lock per book and one per member, held together
A borrow would hold the member's lock and that book's lock at once. That closes the short moment between taking the slot and taking the copy. But two locks taken in different orders by different calls can deadlock, so every call would need the same order, and a mistake shows up only under load.
A lock per book and one per member, never held togetherOur pick
Desks working on different books for different members never wait for each other, and a member's limit is checked and changed under that member's lock. No method holds both locks, so the two can never deadlock. The cost is the short moments between the two steps: a slot counted before its copy is lent, or a returned copy back on the shelf a moment before the member's count goes down. In both, a member can be refused once and succeed on a second try, and no copy is lent twice.
The final design
Library is the core. It owns one BookShelf per book and one MemberAccount per member, and reaches the fine rule and the SMS service only through the FinePolicy and HoldNotifier interfaces.
| S.No. | The question | What we chose | Why |
|---|---|---|---|
| 1 | Should a fine be its own class? | A balance in cents on the member's account | Borrowing only needs to know how much is owed |
| 2 | One class for a book, or a book and its copies? | Book for the title, BookCopy for each barcode | A return names a physical copy |
| 3 | Where does a copy's status live? | In its book's lists, and nothing on the copy | One place says where a copy is, and lending is one step under one lock |
| 4 | Check the member first, or the copy first? | Take the member's slot first, and give it back if no copy is lent | Undoing a slot is one line; undoing a copy is the return path |
| 5 | When is the fine calculated? | From the loan, before the copy is taken back | A failing rule leaves everything as it was |
| 6 | A copy comes back and someone is waiting. Where does it go? | Keep it for the first member waiting, until a pickup deadline | The queue's promise holds, and the member collects with a normal borrow |
| 7 | Who passes on a copy that nobody collects? | Every call on that book checks first, and a nightly sweep catches the rest | Any desk that asks about or changes a book sees it as it should be at that moment |
| 8 | When is the member told their copy is ready? | After each book's lock is released, and a failed message is counted | A slow or failing SMS never holds a book's lock |
| 9 | Where do the locks go? | A lock per book and one per member, never held together | Desks on different books for different members do not wait for each other, and no method can deadlock |
Here is asha's return of MD-1 on 19 March, while ravi and meera wait:
- The desk calls
Library.returnCopy("MD-1").isbnOfCopyfinds the ISBN, andBookShelf.loanOfreads asha's loan under the shelf's lock and lets go of it. FinePolicy.fineForworks out $15 for three days late, with no lock held. A rule that threw here would leave the copy on loan.BookShelf.takeBacktakes the shelf's lock again. It checks that the same loan is still there, works out the pickup deadline, runsexpireKept, and removes the loan. Thenarrivekeeps MD-1 for ravi until 22 March and adds aHoldReadynotice to the list. The lock is released whentakeBackreturns.MemberAccount.endLoantakes asha's own lock, frees her slot and adds $15 to what she owes.sendpasses the notice to theHoldNotifier, the outside call, with no lock held.returnCopyanswersRETURNEDwith the fine and ravi's name.
A borrow is the shorter path. borrow takes a slot with MemberAccount.reserveLoan under the member's lock, and lets go of it. Then BookShelf.lend takes the shelf's lock, passes on any lapsed copies, and lends the copy kept for this member or the first copy on the shelf, with the due date it worked out first. If no copy is lent, releaseLoan gives the slot back. Had ravi come on 21 March, his borrow would have found MD-1 kept for him and lent it. No method holds the member's lock and the shelf's lock at the same time.
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.
package library; import java.time.Clock;import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.Objects;import java.util.Optional;import java.util.OptionalInt;import java.util.OptionalLong;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.atomic.AtomicLong; import book.Book;import book.BookCopy;import book.CopyStatus;import fine.FinePolicy;import hold.HoldNotifier;import hold.HoldReady;import loan.Loan;import member.Member;import result.BorrowOutcome;import result.BorrowResult;import result.HoldOutcome;import result.PaymentOutcome;import result.ReturnOutcome;import result.ReturnResult; /** * The library's front desk. Every counter and the app call these methods, from * many threads at once. Each book has its own lock (in BookShelf) and each * member has their own (in MemberAccount); no method holds both at once. * * Things a person can get wrong (an unknown card, barcode or book, a book with * no copy free) come back as answers. Things only a programmer can get wrong * (a null, a duplicate id while setting up) throw. Notices about kept copies * are sent in a finally block, so a change that was made is always announced. */public final class Library { private final Clock clock; private final LibraryRules rules; private final FinePolicy finePolicy; private final HoldNotifier notifier; private final Map<String, BookShelf> shelves = new ConcurrentHashMap<>(); private final Map<String, String> isbnOfCopy = new ConcurrentHashMap<>(); private final Map<String, MemberAccount> accounts = new ConcurrentHashMap<>(); private final AtomicLong failedNotices = new AtomicLong(); public Library(Clock clock, LibraryRules rules, FinePolicy finePolicy, HoldNotifier notifier) { this.clock = Objects.requireNonNull(clock, "clock"); this.rules = Objects.requireNonNull(rules, "rules"); this.finePolicy = Objects.requireNonNull(finePolicy, "finePolicy"); this.notifier = Objects.requireNonNull(notifier, "notifier"); } public void addBook(Book book) { Objects.requireNonNull(book, "book"); if (shelves.putIfAbsent(book.isbn(), new BookShelf(book, clock, rules)) != null) { throw new IllegalArgumentException(book.isbn() + " is already in the catalogue"); } } public void addCopy(String copyId, String isbn) { BookCopy copy = new BookCopy(copyId, isbn); BookShelf shelf = shelves.get(isbn); if (shelf == null) { throw new IllegalArgumentException(isbn + " is not in the catalogue"); } if (isbnOfCopy.putIfAbsent(copyId, isbn) != null) { throw new IllegalArgumentException(copyId + " is already a copy"); } List<HoldReady> notices = new ArrayList<>(); try { shelf.addCopy(copy, notices); } catch (Throwable t) { isbnOfCopy.remove(copyId, isbn); throw t; } finally { send(notices); } } public void addMember(Member member) { Objects.requireNonNull(member, "member"); if (accounts.putIfAbsent(member.id(), new MemberAccount(member)) != null) { throw new IllegalArgumentException(member.id() + " is already a member"); } } public BorrowResult borrow(String memberId, String isbn) { Objects.requireNonNull(memberId, "memberId"); Objects.requireNonNull(isbn, "isbn"); MemberAccount account = accounts.get(memberId); if (account == null) { return BorrowResult.refused(BorrowOutcome.NO_SUCH_MEMBER); } BookShelf shelf = shelves.get(isbn); if (shelf == null) { return BorrowResult.refused(BorrowOutcome.NO_SUCH_BOOK); } Optional<BorrowOutcome> refusal = account.reserveLoan(rules.blockBorrowingAboveCents()); if (refusal.isPresent()) { return BorrowResult.refused(refusal.get()); } List<HoldReady> notices = new ArrayList<>(); BorrowResult result; try { result = shelf.lend(memberId, notices); } catch (Throwable t) { account.releaseLoan(); throw t; } finally { send(notices); } if (!result.lent()) { account.releaseLoan(); } return result; } public ReturnResult returnCopy(String copyId) { Objects.requireNonNull(copyId, "copyId"); String isbn = isbnOfCopy.get(copyId); if (isbn == null) { return ReturnResult.refused(ReturnOutcome.NO_SUCH_COPY); } BookShelf shelf = shelves.get(isbn); Optional<Loan> found = shelf.loanOf(copyId); if (found.isEmpty()) { return ReturnResult.refused(ReturnOutcome.NOT_ON_LOAN); } Loan loan = found.get(); long fine = finePolicy.fineFor(loan.dueAt(), clock.instant()); if (fine < 0 || fine > FinePolicy.MAX_FINE_CENTS) { throw new IllegalStateException("the fine rule returned " + fine + " cents"); } List<HoldReady> notices = new ArrayList<>(); try { if (!shelf.takeBack(loan, notices)) { return ReturnResult.refused(ReturnOutcome.NOT_ON_LOAN); } accounts.get(loan.memberId()).endLoan(fine); return ReturnResult.returned(loan, fine, keptFor(copyId, notices)); } finally { send(notices); } } public HoldOutcome placeHold(String memberId, String isbn) { Objects.requireNonNull(memberId, "memberId"); Objects.requireNonNull(isbn, "isbn"); if (!accounts.containsKey(memberId)) { return HoldOutcome.NO_SUCH_MEMBER; } BookShelf shelf = shelves.get(isbn); if (shelf == null) { return HoldOutcome.NO_SUCH_BOOK; } List<HoldReady> notices = new ArrayList<>(); HoldOutcome outcome = shelf.placeHold(memberId, notices); send(notices); return outcome; } public PaymentOutcome payFine(String memberId, long cents) { Objects.requireNonNull(memberId, "memberId"); if (cents <= 0) { throw new IllegalArgumentException("a payment must be more than zero"); } MemberAccount account = accounts.get(memberId); if (account == null) { return PaymentOutcome.NO_SUCH_MEMBER; } return account.pay(cents); } /** Passes on every kept copy whose deadline has passed. A nightly job calls this. */ public void expireHolds() { for (BookShelf shelf : shelves.values()) { List<HoldReady> notices = new ArrayList<>(); shelf.expireKept(notices); send(notices); } } /** * Where a copy is, or empty for a barcode that is not one of ours. Even this * question can change state: it passes on lapsed kept copies and sends their notices. */ public Optional<CopyStatus> statusOf(String copyId) { String isbn = isbnOfCopy.get(Objects.requireNonNull(copyId, "copyId")); if (isbn == null) { return Optional.empty(); } List<HoldReady> notices = new ArrayList<>(); try { return shelves.get(isbn).statusOf(copyId, notices); } finally { send(notices); } } /** The members waiting for a book, or empty for an unknown ISBN. Like statusOf, it passes lapsed copies on. */ public Optional<List<String>> waitingFor(String isbn) { BookShelf shelf = shelves.get(Objects.requireNonNull(isbn, "isbn")); if (shelf == null) { return Optional.empty(); } List<HoldReady> notices = new ArrayList<>(); try { return Optional.of(shelf.waiting(notices)); } finally { send(notices); } } public OptionalLong finesOwedCents(String memberId) { MemberAccount account = accounts.get(Objects.requireNonNull(memberId, "memberId")); return account == null ? OptionalLong.empty() : OptionalLong.of(account.finesOwedCents()); } public OptionalInt loansOut(String memberId) { MemberAccount account = accounts.get(Objects.requireNonNull(memberId, "memberId")); return account == null ? OptionalInt.empty() : OptionalInt.of(account.loansOut()); } public long failedNotices() { return failedNotices.get(); } /** Runs with no lock held. A notifier that throws is counted and skipped; the copy stays kept. */ private void send(List<HoldReady> notices) { for (HoldReady notice : notices) { try { notifier.copyReady(notice); } catch (RuntimeException e) { failedNotices.incrementAndGet(); } } } private static String keptFor(String copyId, List<HoldReady> notices) { for (HoldReady notice : notices) { if (notice.copyId().equals(copyId)) { return notice.memberId(); } } return null; }}demo/Main.java runs a small library from 2 March to 15 April. It has five books, one copy each, and three members: asha and ravi on standard cards, and meera on a premium card. Ravi has a phone number on file and meera does not.
--- 2 Mar asha borrows Malgudi Days: LENT copy MD-1, due 16 Mar ravi borrows Malgudi Days: NO_COPY_AVAILABLE ravi places a hold on Malgudi Days: PLACED meera places a hold on Malgudi Days: PLACED ravi places a hold on Malgudi Days again: ALREADY_WAITING waiting for Malgudi Days: [ravi, meera] ravi borrows Wings of Fire: LENT copy WF-1, due 16 Mar kabir borrows Godan: NO_SUCH_MEMBER --- 19 Mar, 3 days after Malgudi Days was due asha returns MD-1 SMS to ravi (98450 12345): Malgudi Days is ready, copy MD-1, collect by 22 Mar 10:00 RETURNED, fine $15.00, now kept for ravi meera borrows Malgudi Days: NO_COPY_AVAILABLE --- 23 Mar, ravi did not come nightly job: expireHolds() SMS to meera failed: no phone number notices that could not be sent: 1 MD-1 is KEPT_FOR_HOLD ravi borrows Malgudi Days: NO_COPY_AVAILABLE meera borrows Malgudi Days: LENT copy MD-1, due 6 Apr meera borrows Malgudi Days: ALREADY_HAS_THIS_BOOK --- 15 Apr, Wings of Fire is 30 days late ravi returns WF-1 RETURNED, fine $150.00, back on the shelf ravi borrows Godan: FINES_DUE ravi pays $100.00: PAID, still owes $50.00 ravi pays $100.00: MORE_THAN_OWED ravi borrows Godan: LENT copy GD-1, due 29 Apr asha borrows Wings of Fire: LENT copy WF-1, due 29 Apr asha borrows Gitanjali: LENT copy GT-1, due 29 Apr asha borrows Train to Pakistan: LENT copy TP-1, due 29 Apr asha borrows Malgudi Days: LIMIT_REACHED asha has 3 books out, the most a STANDARD card allows
Notice four things in the output. Ravi's second hold is ALREADY_WAITING, and the queue stays [ravi, meera]. On 19 March, MD-1 is kept for ravi, so meera's borrow is refused even though the copy is in the building. On 23 March the nightly job passes MD-1 to meera. Her SMS fails and is counted, yet the copy stays kept and she borrows it the same day. And ravi's $150 fine stops his borrowing until he pays it down to $50, while asha is stopped by her plan's limit of three books.
Follow-up questions
A follow-up adds a requirement to see how the design bends. For each one, say which classes change and which do not.
| The interviewer asks | What changes | What does not |
|---|---|---|
| "Search by title or author." | An index from words to ISBNs beside shelves, filled in addBook | Lending, returns, holds, fines |
| "Let members renew a loan." | A renew method on BookShelf that moves the due date, refused if someone is waiting, and a matching method on Library | Fines, holds, accounts |
| "Let a member cancel a hold." | A cancelHold on BookShelf. A cancelled kept copy goes through arrive, like an expired one | Lending, returns, fines |
| "Charge a damaged book's price." | A way to add a charge to MemberAccount that is not a late fine, and a markDamaged on the shelf that removes the copy | Holds, the fine rule |
| "Retry SMS messages that failed." | send puts failed notices in a queue, and a job retries them | Everything under the locks |
| "Several branches, with returns at any branch." | A copy belongs to a home branch. A return at another branch starts a transfer, and the copy arrives at its home BookShelf later | FinePolicy, MemberAccount |
| "Members pay fines online." | Nothing in the design: the payment service calls payFine | Everything |
| "Run on several servers." | Loans, queues and balances move to a database, and each book's lock becomes a row lock or a version check | FinePolicy, the records |
Most rows add a method to BookShelf or a class beside the core, and Library changes only to pass the new call through. 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 clear classes with sensible names, a working borrow and return, the member's limit, and a fine for a late return. They separate a book from its copies, and they mention that several desks means some locking.
Senior
A senior candidate shows everything above and gives the reasons. They keep each copy's place in one set of lists, put the fine rule behind an interface, and use cents for money and a clock passed in for time. They design holds with a pickup deadline and explain who passes on a copy nobody collects. They put the locks per book and per member, and explain why the order of the two steps in borrow matters.
Staff+
A staff candidate leads the conversation through what can go wrong. They point out the short moments between the two locks and why they are acceptable. They explain what a failed SMS means for the member, and what a crash between takeBack and endLoan would leave behind. They can also say how the design changes when the state moves to a database shared by several servers.
Common mistakes
- One
Bookclass with a count of copies. A return names a physical copy, and a count cannot say which one came back or who had it. - A status field on each copy, checked and set in two steps. Two desks can both see the last copy as free.
- Putting a returned copy straight back on the shelf. The queue then promises nothing, because a walk-in can take the copy first.
- No deadline on a kept copy. One member who never comes back holds the copy for ever, and everyone behind them waits.
- Calculating the fine after the copy is back. A fine rule that throws then leaves the copy kept for someone else and the old loan still counted.
- Sending the SMS while holding a book's lock. A slow SMS service then stalls every desk working on that book.
doublefor money, andInstant.now()inside the classes. Both make fines hard to get right and impossible to test.
Summary
- Ask about copies, limits, fines, holds and desks first. Each answer changes the code.
- Use a
Bookfor the title and aBookCopyfor each barcode. A loan points at a copy. - Keep every copy of a book in one of three collections on its
BookShelf, and change them under one lock. - Take the member's slot first and the copy second, and give the slot back if no copy is lent.
- Calculate the fine before anything changes, and keep the fine rule behind an interface.
- Keep a returned copy for the first member waiting until a pickup deadline, and check the deadline on every borrow, return and hold on that book.
- Send messages after the locks are released, and count the ones that fail.