The library prompt sounds like the easiest one on the list. Books, members, issue, return. Most answers come out as a Book class with an isIssued flag and a Member with a list of books, and they pass the first ten minutes. Then the interviewer asks what happens when three people want the only copy of Design Patterns, and the design has nowhere to put them.
Two ideas carry this problem. A title and a copy are different things: the catalogue has one Designing Data-Intensive Applications, the shelf has three of them with three barcodes. And people wait for a title, not for a copy. Get those two right and holds, renewals and fines fall into place. Get them wrong and every later feature is a patch.
The code below is about 560 lines in each language, and includes a one-year simulation that puts numbers on a policy question most answers never reach: how long should a reserved book sit on the hold shelf?
What the library needs from the system
In:
- A catalogue of titles (ISBN, title, authors, subject) and the physical copies of each, each with a barcode and a replacement price.
- Search by words in the title, author or subject.
- Members on a plan. Students borrow up to 3 books for 14 days; faculty up to 10 for 30 days; the public up to 2 for 14 days. Plans also set how many renewals you get and how fines work.
- Borrow at the desk with a specific copy in hand, or request a title from the app: you get a copy if one is on the shelf, otherwise you join the queue.
- A copy that comes back while people are waiting goes to the hold shelf for the first person in the queue, for a fixed number of days. If they do not collect it, it moves to the next person.
- Renew a loan, unless someone is waiting for that title.
- Fines for late returns, a block on borrowing above ₹100 of unpaid fines or while holding an overdue book, payments, and lost books charged at their price.
- Several members and librarians acting at the same time.
Not in this version, and I would say so out loud:
- Several branches and transfers between them. It changes where a copy lives and adds a “in transit” state; the extension is below.
- E-books and licences. A licence that allows 3 concurrent readers looks like 3 copies, but it expires and never comes back late, so the fine and hold-shelf logic do not apply.
- Login, notifications by SMS or email, the payment gateway. Notifications appear here as a list of events; something outside sends them.
- Acquisitions, cataloguing workflows, inter-library loans.
A title is not a book on a shelf
The first decision, and the one that decides whether the rest is clean:
Bookis the title. ISBN, title, authors, subject, its list of copies, and its hold queue.Copyis one physical book. Barcode, price, status, and if it is on the hold shelf, who it is held for and until when.Loanlinks a copy to a member: start day, due day, renewals, return day. It is a record, not a status flag. A copy’s history is its loans.Memberhas a plan, open loans and unpaid fines.Planis data: limits, loan length, renewals, and which fine policy applies.Libraryis the one service object that every operation goes through.
Put the hold queue on the copy and you get the classic bug: Bela reserves DP-1, DP-2 comes back first, and it goes back on the open shelf while she keeps waiting for the one she happened to pick. A queue on the title gives the first returned copy to the first person in line, which is what any librarian would do by hand.
Two things are missing on purpose. There is no Librarian class. A librarian is a member of staff with permissions, which is an authorisation concern, and in an interview a Librarian extends Member class with addBook() on it adds a box to the diagram and nothing else. And there is no Student or Faculty subclass of Member: they behave identically and differ only in numbers, so they are two instances of Plan.
classDiagram
class Library {
+today: int
+hold_days: int
+add_book(isbn, title, authors, subject)
+add_copy(isbn, barcode, price)
+search(query) list~Book~
+checkout(member_id, barcode) Loan
+request(member_id, isbn) Loan or int
+renew(barcode) Loan
+return_copy(barcode) int
+report_lost(barcode) int
+pay(member_id, amount)
+advance_to(day) int
}
class Book {
+isbn: str
+title: str
+authors: str
+subject: str
+holds: deque
-lock
}
class Copy {
+barcode: str
+price: int
+status: Status
+held_for: str
+hold_until: int
+move(to)
}
class Status {
<<enumeration>>
AVAILABLE
ON_LOAN
ON_HOLD_SHELF
LOST
}
class Loan {
+id: int
+start: int
+due: int
+renewals: int
+returned: int
+waited: int
}
class Member {
+id: str
+name: str
+fines_due: int
-lock
}
class Plan {
+max_loans: int
+loan_days: int
+max_renewals: int
}
class FinePolicy {
<<interface>>
+fine(days_late, price) int
}
Library "1" o-- "*" Book
Library "1" o-- "*" Member
Book "1" *-- "*" Copy
Copy --> Status
Copy "1" --> "0..1" Loan : current
Member "1" --> "*" Loan : open
Member --> Plan
Plan --> FinePolicy
FinePolicy <|.. NoFine
FinePolicy <|.. PerDay
FinePolicy <|.. TieredThe life of one copy
A copy has four states, and the code lists every legal move in one table:
| From | To | When |
|---|---|---|
| available | on loan | borrowed off the shelf |
| available | on hold shelf | a new copy is added while people are waiting |
| on hold shelf | on loan | the person it is held for collects it |
| on hold shelf | on hold shelf | not collected in time, next person in the queue |
| on hold shelf | available | not collected, nobody else waiting |
| on loan | available | returned, nobody waiting |
| on loan | on hold shelf | returned, someone waiting |
| on loan | lost | reported lost |
Copy.move() refuses anything else with an assertion, not a user-facing error. “Return a copy that is not on loan” is a user mistake and gets a polite refusal. “A lost copy became available” is a bug in my code, and I want it to fail loudly in tests.
The rule that decides where a free copy goes lives in one private method, _route. Returns, newly added copies and expired holds all call it. Skip it in any one of those paths and you get the quiet version of the bug: a new copy goes straight to the open shelf and a member who walks in takes a book that five people are queueing for. The table earned its keep on the first run, too. My first add_copy called _route even when nobody was waiting, and the assertion fired at once on “available → available”.
Holds and the hold shelf
The queue is a FIFO of (member, day the hold was placed) on the title. request(member, isbn) does what a user means by “I want this book”: if a copy is already held for you, you get it; if one is on the open shelf, you get it; otherwise you join the queue and are told your position. There is no separate place_hold that can be called while copies are sitting on the shelf, so “reserve a book that is right there” is impossible rather than validated.
A copy on the hold shelf is taken out of circulation for hold_days. advance_to(day) is the nightly job: any copy whose hold has run out is routed again, to the next person or back to the shelf. Time is an integer day passed in, never datetime.now() read inside the model. That is what makes demo 3 below reproducible, and it is the single change that makes a library system testable.
How long should the hold shelf be? Short, and copies bounce between people who did not show up. Long, and a popular book sits unread on a trolley. The simulation measures it further down.
Fines are policy, plans are data
Three fine rules, one interface, fine(days_late, price) → rupees:
- Students: ₹5 a day, capped at ₹200.
- Public: ₹2 a day for the first week, then ₹10 a day, never more than the price of the book.
- Faculty: no fines. (Many university libraries do this and then chase faculty by email instead. It is a policy choice, and the design should not have an opinion on it.)
The fine is computed once, at return, and added to the member’s balance. It is not recomputed on every page load from “today minus due date”, because then a policy change next year would silently change fines people already paid.
Borrowing is blocked at ₹100 of unpaid fines, or while the member has any overdue book. That second rule matters more than the money: in the demo, Bela cannot collect the book she queued for because she is sitting on an overdue copy of Effective Java.
Renewals are refused if anyone is waiting for the title, if the plan’s renewals are used up, or if the loan is already overdue. A renewal extends the due date to today plus the loan period, not due date plus the loan period. Renewing on day 1 of a 14-day loan should not give you 28 days.
Which patterns earn their place
Strategy, for fines. Three real rules that differ in shape, not just in a number: flat with a cap, tiered with the book’s price as the cap, and none. Each is a few lines and can be tested on its own. Adding “no fines during the exam week” is a new class, or a wrapper around an existing one.
State, as a transition table rather than classes. The copy has four states and the behaviour per state is one line: which moves are legal. Four CopyState subclasses with checkout(), return(), hold() and lose() on each would be 16 methods, most of them “throw”. Compare the ATM lesson, where the session really does behave differently in each state and the State pattern pays for itself. Here a table is clearer.
Facade. Library is the only entry point. It is where the lock order lives and where each operation checks its rules in one place, so the web controller, the desk terminal and the nightly job cannot each implement “can this person borrow” slightly differently.
Considered and turned down:
- Observer for “your book is ready”. The event is real, but calling an email sender inside
return_copymeans a slow SMTP server holds the lock on that title. The code appends to an event list instead; in production it is an outbox table written in the same transaction and sent by a worker. - Inheritance for member types.
Student extends Memberwith an overriddenmaxBooks()is the most common answer and the weakest: the types differ only in numbers, and the day the library adds “research scholar” you need a new class and a deploy instead of a new row. - Singleton
Library. A real system has several branches and tests want a fresh library each. Pass it in. - Factory for books. Every book is constructed the same way. There is nothing to choose.
- Repository interfaces for every entity. In production yes, in 45 minutes no. Say where the database goes (next section) and move on.
One lock per title
Copies and the hold queue of one title always change together: a return moves a copy and pops the queue in one step. So the lock is per Book. Operations that also touch a member (their loan count, their fines) take the member’s lock as well, always in the order book, then member. Nothing takes them the other way, so two operations can never wait for each other in a cycle.
Two requests for different titles never contend. Two members racing for the last copy of the same title queue up on that title’s lock, which is the only place the race exists.
To check that the lock is doing real work, I removed both locks from request in the Java version and ran demo 6 (8 threads, 3 copies) 2,000 times, three times over. 75, 85 and 98 of the 2,000 runs went wrong. In 45 to 76 of them more than 3 loans were handed out for 3 copies, which means two members walked away owning the same barcode; in 23 to 30 two members got the same queue position and one of them silently fell out of the queue. With the locks, 0 of 4,000. A 4% failure rate is exactly the kind of bug that passes every test and shows up during admission week.
In a database the per-title lock becomes SELECT ... FOR UPDATE on the title row, or a conditional update on the copy: UPDATE copy SET status='ON_LOAN', member_id=? WHERE barcode=? AND status='AVAILABLE', and check that one row changed.
The code
Both versions were run on the box this lesson was written on (Python 3.13.5, OpenJDK 21.0.13) and print byte-for-byte identical output; I ran each five times. Demo 6 uses threads, but it prints only counts that do not depend on which thread wins. Demo 7 is a one-year simulation driven by the same 64-bit LCG in both languages. Files and expected-output.txt are in course-code/low-level-design/17/ in the course repository.
Before reading:
requestchecks your own held copy first, then the open shelf, then queues you. The order matters: a member at the front of the queue should get the copy reserved for them, not a different one that happens to be free.checkoutis the desk: the member is holding a specific copy. It refuses a copy that is on the hold shelf for someone else, which is the situation where a librarian would otherwise hand over the wrong book._routeis the only place that decides where a free copy goes.- In the simulation, each member asks for a book on 3% of days, biased towards low-numbered titles (the minimum of two random picks), returns 70% of loans on time, 20% up to a week late and 10% up to five weeks late, and collects a held copy on any given day with 30% probability.
Python
"""Library management system: titles vs physical copies, loans with plan limits,
one hold queue per title, a hold shelf that expires, renewals, fines as a strategy,
and a one-year simulation driven by a fixed LCG.
Run: python3 library.py
"""
from __future__ import annotations
import re
import threading
from abc import ABC, abstractmethod
from collections import deque
from dataclasses import dataclass, field
from enum import Enum
class LibraryError(Exception):
pass
class Status(Enum):
AVAILABLE = "available"
ON_LOAN = "on loan"
ON_HOLD_SHELF = "on hold shelf"
LOST = "lost"
# Every legal move of a physical copy. Anything else is a bug, not a user error.
ALLOWED = {
(Status.AVAILABLE, Status.ON_LOAN),
(Status.AVAILABLE, Status.ON_HOLD_SHELF), # copy added while people are waiting
(Status.ON_HOLD_SHELF, Status.ON_LOAN), # collected
(Status.ON_HOLD_SHELF, Status.ON_HOLD_SHELF), # not collected, next in queue
(Status.ON_HOLD_SHELF, Status.AVAILABLE), # not collected, nobody else waiting
(Status.ON_LOAN, Status.AVAILABLE),
(Status.ON_LOAN, Status.ON_HOLD_SHELF),
(Status.ON_LOAN, Status.LOST),
}
# ---------------- fine policies (Strategy) ----------------
class FinePolicy(ABC):
@abstractmethod
def fine(self, days_late: int, price: int) -> int:
"""Fine in rupees for returning a copy `days_late` days after its due date."""
class NoFine(FinePolicy):
def fine(self, days_late, price):
return 0
class PerDay(FinePolicy):
def __init__(self, rate: int, cap: int) -> None:
self.rate, self.cap = rate, cap
def fine(self, days_late, price):
return min(days_late * self.rate, self.cap)
class Tiered(FinePolicy):
"""`low` per day for the first `days` days, `high` per day after that, never more than the book."""
def __init__(self, low: int, days: int, high: int) -> None:
self.low, self.days, self.high = low, days, high
def fine(self, days_late, price):
first = min(days_late, self.days)
return min(first * self.low + (days_late - first) * self.high, price)
@dataclass(frozen=True)
class Plan:
name: str
max_loans: int
loan_days: int
max_renewals: int
fines: FinePolicy
STUDENT = Plan("student", 3, 14, 1, PerDay(5, 200))
FACULTY = Plan("faculty", 10, 30, 3, NoFine())
PUBLIC = Plan("public", 2, 14, 1, Tiered(2, 7, 10))
BLOCK_AT = 100 # rupees of unpaid fines that stop new loans
# ---------------- entities ----------------
@dataclass
class Loan:
id: int
barcode: str
isbn: str
member_id: str
start: int
due: int
waited: int # days spent in the hold queue before this loan, 0 if borrowed off the shelf
renewals: int = 0
returned: int | None = None
@dataclass
class Copy:
barcode: str
isbn: str
price: int
status: Status = Status.AVAILABLE
held_for: str | None = None
hold_until: int = 0
hold_since: int = 0
loan: Loan | None = None
def move(self, to: Status) -> None:
if (self.status, to) not in ALLOWED:
raise AssertionError(f"{self.barcode}: {self.status.value} -> {to.value}")
self.status = to
@dataclass
class Book:
"""A title. Copies and the hold queue change together, so they share one lock."""
isbn: str
title: str
authors: str
subject: str
copies: list[Copy] = field(default_factory=list)
holds: deque = field(default_factory=deque) # (member_id, day the hold was placed)
lock: threading.Lock = field(default_factory=threading.Lock, repr=False)
@dataclass
class Member:
id: str
name: str
plan: Plan
loans: dict[str, Loan] = field(default_factory=dict) # barcode -> open loan
fines_due: int = 0
lock: threading.Lock = field(default_factory=threading.Lock, repr=False)
def words(text: str) -> list[str]:
return re.findall(r"[a-z0-9]+", text.lower())
# ---------------- the service ----------------
class Library:
"""Lock order is always book, then member. Nothing takes them the other way round."""
def __init__(self, hold_days: int = 3) -> None:
self.hold_days = hold_days
self.today = 1
self.books: dict[str, Book] = {}
self.copies: dict[str, Copy] = {}
self.members: dict[str, Member] = {}
self.index: dict[str, set[str]] = {}
self.events: list[str] = []
self._next_loan = 1
self._id_lock = threading.Lock()
# catalog
def add_book(self, isbn, title, authors, subject) -> None:
self.books[isbn] = Book(isbn, title, authors, subject)
for w in set(words(f"{title} {authors} {subject}")):
self.index.setdefault(w, set()).add(isbn)
def add_copy(self, isbn, barcode, price) -> None:
book = self.books[isbn]
with book.lock:
copy = Copy(barcode, isbn, price)
book.copies.append(copy)
self.copies[barcode] = copy
if book.holds: # people were already waiting for this title
self._route(book, copy)
def search(self, query: str) -> list[Book]:
sets = [self.index.get(w, set()) for w in words(query)]
hits = set.intersection(*sets) if sets else set()
return sorted((self.books[i] for i in hits), key=lambda b: b.title)
def register(self, member_id, name, plan) -> None:
self.members[member_id] = Member(member_id, name, plan)
# borrowing
def checkout(self, member_id: str, barcode: str) -> Loan:
"""At the desk: the member is holding this exact copy."""
copy = self.copies[barcode]
book, m = self.books[copy.isbn], self.members[member_id]
with book.lock, m.lock:
self._can_borrow(m)
if copy.status is Status.ON_HOLD_SHELF and copy.held_for != m.id:
raise LibraryError(f"{barcode} is on the hold shelf for {copy.held_for}")
if copy.status not in (Status.AVAILABLE, Status.ON_HOLD_SHELF):
raise LibraryError(f"{barcode} is {copy.status.value}")
return self._lend(copy, m)
def request(self, member_id: str, isbn: str) -> Loan | int:
"""In the app: lend any copy if one is free, otherwise join the queue.
Returns the loan, or the member's position in the queue."""
book, m = self.books[isbn], self.members[member_id]
with book.lock, m.lock:
self._can_borrow(m)
for c in book.copies:
if c.status is Status.ON_HOLD_SHELF and c.held_for == m.id:
return self._lend(c, m)
if any(l.isbn == isbn for l in m.loans.values()):
raise LibraryError(f"{m.name} already has {book.title}")
for pos, (who, _) in enumerate(book.holds, 1):
if who == m.id:
raise LibraryError(f"{m.name} is already number {pos} for {book.title}")
for c in book.copies:
if c.status is Status.AVAILABLE:
return self._lend(c, m)
book.holds.append((m.id, self.today))
return len(book.holds)
def renew(self, barcode: str) -> Loan:
copy = self.copies[barcode]
book = self.books[copy.isbn]
with book.lock:
loan = copy.loan
if loan is None:
raise LibraryError(f"{barcode} is not on loan")
m = self.members[loan.member_id]
with m.lock:
if book.holds:
raise LibraryError(f"{len(book.holds)} waiting for {book.title}")
if loan.renewals >= m.plan.max_renewals:
raise LibraryError(f"already renewed {loan.renewals} time(s)")
if self.today > loan.due:
raise LibraryError(f"overdue since day {loan.due}")
loan.due = self.today + m.plan.loan_days
loan.renewals += 1
return loan
def return_copy(self, barcode: str) -> int:
"""Returns the fine charged, in rupees."""
copy = self.copies[barcode]
book = self.books[copy.isbn]
with book.lock:
loan = copy.loan
if loan is None:
raise LibraryError(f"{barcode} is not on loan")
m = self.members[loan.member_id]
with m.lock:
fine = m.plan.fines.fine(max(0, self.today - loan.due), copy.price)
m.fines_due += fine
loan.returned = self.today
del m.loans[barcode]
copy.loan = None
self._route(book, copy)
return fine
def report_lost(self, barcode: str) -> int:
copy = self.copies[barcode]
book = self.books[copy.isbn]
with book.lock:
loan = copy.loan
if loan is None:
raise LibraryError(f"{barcode} is not on loan")
m = self.members[loan.member_id]
with m.lock:
m.fines_due += copy.price
loan.returned = self.today
del m.loans[barcode]
copy.loan = None
copy.move(Status.LOST)
return copy.price
def pay(self, member_id: str, amount: int) -> None:
m = self.members[member_id]
with m.lock:
if not 0 < amount <= m.fines_due:
raise LibraryError(f"{m.name} owes Rs {m.fines_due}, cannot pay Rs {amount}")
m.fines_due -= amount
def advance_to(self, day: int) -> int:
"""Start a new day: copies nobody collected go to the next person. Returns how many expired."""
self.today = day
expired = 0
for book in self.books.values():
with book.lock:
for c in book.copies:
if c.status is Status.ON_HOLD_SHELF and c.hold_until < day:
expired += 1
self.events.append(f"day {day}: {c.barcode} not collected by {c.held_for}")
self._route(book, c)
return expired
# internals: callers hold the book lock (and the member lock where a member is touched)
def _can_borrow(self, m: Member) -> None:
if len(m.loans) >= m.plan.max_loans:
raise LibraryError(f"{m.name} has {len(m.loans)} books, the {m.plan.name} limit")
if m.fines_due >= BLOCK_AT:
raise LibraryError(f"{m.name} owes Rs {m.fines_due} in fines")
for l in m.loans.values():
if l.due < self.today:
raise LibraryError(f"{m.name} has {l.barcode} overdue since day {l.due}")
def _lend(self, copy: Copy, m: Member) -> Loan:
waited = self.today - copy.hold_since if copy.status is Status.ON_HOLD_SHELF else 0
with self._id_lock:
loan_id, self._next_loan = self._next_loan, self._next_loan + 1
loan = Loan(loan_id, copy.barcode, copy.isbn, m.id, self.today,
self.today + m.plan.loan_days, waited)
copy.move(Status.ON_LOAN)
copy.held_for, copy.loan = None, loan
m.loans[copy.barcode] = loan
return loan
def _route(self, book: Book, copy: Copy) -> None:
"""A copy is free: give it to the head of the queue, or put it back on the shelf."""
if book.holds:
who, since = book.holds.popleft()
copy.move(Status.ON_HOLD_SHELF)
copy.held_for, copy.hold_since = who, since
copy.hold_until = self.today + self.hold_days
self.events.append(f"day {self.today}: {copy.barcode} held for {who} until day {copy.hold_until}")
else:
copy.held_for = None
copy.move(Status.AVAILABLE)
# ---------------- demo ----------------
def attempt(label: str, fn) -> None:
try:
r = fn()
if isinstance(r, Loan):
print(f" {label}: loan #{r.id}, due day {r.due}")
elif isinstance(r, int) and "request" in label:
print(f" {label}: queued, position {r}")
else:
print(f" {label}: ok" + ("" if r is None else f", {r}"))
except LibraryError as e:
print(f" {label}: refused: {e}")
def flush(lib: Library) -> None:
for e in lib.events:
print(f" event {e}")
lib.events.clear()
def build() -> Library:
lib = Library(hold_days=3)
lib.add_book("EJ", "Effective Java", "Joshua Bloch", "java")
lib.add_book("DP", "Design Patterns", "Gamma Helm Johnson Vlissides", "software design")
lib.add_book("DD", "Designing Data-Intensive Applications", "Martin Kleppmann", "databases")
lib.add_book("CC", "Clean Code", "Robert C. Martin", "software design")
for isbn, n, price in [("EJ", 2, 899), ("DP", 1, 1050), ("DD", 3, 1850), ("CC", 1, 650)]:
for i in range(1, n + 1):
lib.add_copy(isbn, f"{isbn}-{i}", price)
lib.register("aman", "Aman", STUDENT)
lib.register("bela", "Bela", STUDENT)
lib.register("chirag", "Chirag", FACULTY)
lib.register("divya", "Divya", PUBLIC)
return lib
def demo() -> None:
lib = build()
print("1) Search is exact words over title, author and subject")
for q in ["design", "martin", "data intensive", "designs"]:
hits = lib.search(q)
shown = ", ".join(
f"{b.title} ({sum(c.status is Status.AVAILABLE for c in b.copies)}/{len(b.copies)})"
for b in hits) or "nothing"
print(f" {q!r:17} -> {shown}")
print("\n2) Plan limits, day 1")
attempt("aman checkout EJ-1", lambda: lib.checkout("aman", "EJ-1"))
attempt("aman checkout DD-1", lambda: lib.checkout("aman", "DD-1"))
attempt("aman checkout CC-1", lambda: lib.checkout("aman", "CC-1"))
attempt("aman checkout EJ-2", lambda: lib.checkout("aman", "EJ-2"))
attempt("chirag checkout DP-1", lambda: lib.checkout("chirag", "DP-1"))
attempt("chirag checkout EJ-1", lambda: lib.checkout("chirag", "EJ-1"))
print("\n3) Days 2-27: one copy of Design Patterns, two people waiting")
lib.advance_to(2)
attempt("bela request DP", lambda: lib.request("bela", "DP"))
attempt("divya request DP", lambda: lib.request("divya", "DP"))
attempt("bela request DP", lambda: lib.request("bela", "DP"))
attempt("bela request EJ", lambda: lib.request("bela", "EJ"))
lib.advance_to(14)
attempt("aman renew CC-1 (day 14)", lambda: lib.renew("CC-1"))
lib.advance_to(20)
attempt("chirag renew DP-1 (day 20)", lambda: lib.renew("DP-1"))
lib.advance_to(22)
attempt("chirag return DP-1 (day 22)", lambda: f"fine Rs {lib.return_copy('DP-1')}")
flush(lib)
attempt("divya checkout DP-1", lambda: lib.checkout("divya", "DP-1"))
attempt("bela checkout DP-1", lambda: lib.checkout("bela", "DP-1"))
lib.advance_to(26)
flush(lib)
lib.advance_to(27)
attempt("divya request DP (day 27)", lambda: lib.request("divya", "DP"))
attempt("aman renew CC-1 (day 27)", lambda: lib.renew("CC-1"))
print("\n4) Days 29-75: fines")
lib.advance_to(29)
attempt("aman return EJ-1 (day 29)", lambda: f"fine Rs {lib.return_copy('EJ-1')}")
attempt("aman return DD-1 (day 29)", lambda: f"fine Rs {lib.return_copy('DD-1')}")
lib.advance_to(52)
attempt("divya return DP-1 (day 52)", lambda: f"fine Rs {lib.return_copy('DP-1')}")
lib.advance_to(75)
attempt("aman return CC-1 (day 75)", lambda: f"fine Rs {lib.return_copy('CC-1')}")
attempt("bela return EJ-2 (day 75)", lambda: f"fine Rs {lib.return_copy('EJ-2')}")
attempt("aman checkout DD-1", lambda: lib.checkout("aman", "DD-1"))
attempt("aman pay Rs 500", lambda: lib.pay("aman", 500))
attempt("aman pay Rs 300", lambda: lib.pay("aman", 300))
attempt("aman checkout DD-1", lambda: lib.checkout("aman", "DD-1"))
print(f" aman still owes Rs {lib.members['aman'].fines_due}, under the Rs {BLOCK_AT} block")
print("\n5) A lost copy is charged at its price and leaves circulation")
attempt("aman reports DD-1 lost", lambda: f"charged Rs {lib.report_lost('DD-1')}")
attempt("chirag checkout DD-1", lambda: lib.checkout("chirag", "DD-1"))
dd = lib.books["DD"]
print(" DD copies: " + ", ".join(f"{c.barcode} {c.status.value}" for c in dd.copies))
print("\n6) Eight members request 3 copies at the same moment")
lib.add_book("PP", "The Pragmatic Programmer", "David Thomas Andrew Hunt", "software craft")
for i in range(1, 4):
lib.add_copy("PP", f"PP-{i}", 700)
for i in range(1, 9):
lib.register(f"m{i}", f"M{i}", STUDENT)
results: list = []
start = threading.Barrier(8)
def worker(mid: str) -> None:
start.wait()
results.append(lib.request(mid, "PP"))
threads = [threading.Thread(target=worker, args=(f"m{i}",)) for i in range(1, 9)]
for t in threads:
t.start()
for t in threads:
t.join()
loans = [r for r in results if isinstance(r, Loan)]
positions = sorted(r for r in results if not isinstance(r, Loan))
pp = lib.books["PP"]
print(f" loans: {len(loans)}, loan ids distinct: {len({l.id for l in loans}) == len(loans)}")
print(f" queue positions handed out: {positions}, queue length: {len(pp.holds)}")
print(f" copies on loan: {sum(c.status is Status.ON_LOAN for c in pp.copies)}")
print("\n7) One simulated year, 120 members, 40 titles: hold shelf 3 days vs 7 days")
for days in (3, 7):
simulate(days)
# ---------------- simulation ----------------
class Lcg:
MASK = (1 << 64) - 1
def __init__(self, seed: int) -> None:
self.s = seed & self.MASK
def next(self, n: int) -> int:
self.s = (self.s * 6364136223846793005 + 1442695040888963407) & self.MASK
return (self.s >> 33) % n
def tenths(num: int, den: int) -> str:
if den == 0:
return "n/a"
t = num * 10 // den
return f"{t // 10}.{t % 10}"
def simulate(hold_days: int) -> None:
rnd = Lcg(2026)
lib = Library(hold_days)
for t in range(40):
lib.add_book(f"T{t:02d}", f"Title {t:02d}", "Author", "subject")
for c in range(1 + rnd.next(3)):
lib.add_copy(f"T{t:02d}", f"T{t:02d}-{c + 1}", 300 + 100 * rnd.next(15))
for i in range(120):
plan = FACULTY if i % 10 == 0 else PUBLIC if i % 5 == 1 else STUDENT
lib.register(f"u{i:03d}", f"u{i:03d}", plan)
planned: dict[int, int] = {} # loan id -> day the member brings it back
s = dict(loans=0, late=0, fines=0, renew_ok=0, renew_waiting=0, queued=0, collected=0,
waited=0, expired=0, shelf_days=0, longest=0, refused_limit=0, refused_fines=0,
refused_overdue=0)
def plan_return(loan: Loan) -> None:
r = rnd.next(100)
if r < 70:
planned[loan.id] = loan.start + 1 + rnd.next(loan.due - loan.start)
elif r < 90:
planned[loan.id] = loan.due + 1 + rnd.next(7)
else:
planned[loan.id] = loan.due + 8 + rnd.next(30)
for day in range(1, 366):
s["expired"] += lib.advance_to(day)
lib.events.clear()
for m in lib.members.values():
for loan in sorted(m.loans.values(), key=lambda l: l.id):
if day == loan.due and planned[loan.id] > loan.due:
try:
lib.renew(loan.barcode)
s["renew_ok"] += 1
except LibraryError as e:
if "waiting" in str(e):
s["renew_waiting"] += 1
if planned[loan.id] == day:
fine = lib.return_copy(loan.barcode)
if loan.returned > loan.due:
s["late"] += 1
s["fines"] += fine
held = [c for b in lib.books.values() for c in b.copies
if c.status is Status.ON_HOLD_SHELF and c.held_for == m.id]
want = None
if held and rnd.next(10) < 3:
want = held[0].isbn
elif rnd.next(100) < 3:
want = f"T{min(rnd.next(40), rnd.next(40)):02d}"
if want is None:
continue
try:
r = lib.request(m.id, want)
except LibraryError as e:
msg = str(e)
if "limit" in msg:
s["refused_limit"] += 1
elif "fines" in msg:
s["refused_fines"] += 1
lib.pay(m.id, m.fines_due)
elif "overdue" in msg:
s["refused_overdue"] += 1
continue
if isinstance(r, Loan):
s["loans"] += 1
if r.waited:
s["collected"] += 1
s["waited"] += r.waited
plan_return(r)
else:
s["queued"] += 1
s["longest"] = max(s["longest"], r)
s["shelf_days"] += sum(c.status is Status.ON_HOLD_SHELF
for b in lib.books.values() for c in b.copies)
print(f" hold shelf {hold_days} days:")
print(f" loans {s['loans']}, returned late {s['late']}, fines Rs {s['fines']}")
print(f" renewals ok {s['renew_ok']}, refused because someone was waiting {s['renew_waiting']}")
print(f" joined a queue {s['queued']}, longest queue {s['longest']}")
print(f" holds collected {s['collected']}, expired {s['expired']}, "
f"average wait {tenths(s['waited'], s['collected'])} days")
print(f" copy-days spent on the hold shelf {s['shelf_days']}")
print(f" refused: at limit {s['refused_limit']}, fines {s['refused_fines']}, "
f"overdue book {s['refused_overdue']}")
if __name__ == "__main__":
demo()
Java
// Library management system: titles vs physical copies, loans with plan limits,
// one hold queue per title, a hold shelf that expires, renewals, fines as a strategy,
// and a one-year simulation driven by a fixed LCG.
// Run: javac Library.java && java Library
import java.util.*;
import java.util.concurrent.CyclicBarrier;
import java.util.function.Supplier;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Library {
static class LibraryError extends RuntimeException {
LibraryError(String msg) { super(msg); }
}
enum Status {
AVAILABLE("available"), ON_LOAN("on loan"), ON_HOLD_SHELF("on hold shelf"), LOST("lost");
final String label;
Status(String label) { this.label = label; }
}
// Every legal move of a physical copy. Anything else is a bug, not a user error.
static final Map<Status, EnumSet<Status>> ALLOWED = new EnumMap<>(Map.of(
Status.AVAILABLE, EnumSet.of(Status.ON_LOAN, Status.ON_HOLD_SHELF),
Status.ON_HOLD_SHELF, EnumSet.of(Status.ON_LOAN, Status.ON_HOLD_SHELF, Status.AVAILABLE),
Status.ON_LOAN, EnumSet.of(Status.AVAILABLE, Status.ON_HOLD_SHELF, Status.LOST),
Status.LOST, EnumSet.noneOf(Status.class)));
// ---------------- fine policies (Strategy) ----------------
interface FinePolicy { int fine(int daysLate, int price); }
static class NoFine implements FinePolicy {
public int fine(int daysLate, int price) { return 0; }
}
static class PerDay implements FinePolicy {
final int rate, cap;
PerDay(int rate, int cap) { this.rate = rate; this.cap = cap; }
public int fine(int daysLate, int price) { return Math.min(daysLate * rate, cap); }
}
/** low per day for the first `days` days, high per day after that, never more than the book. */
static class Tiered implements FinePolicy {
final int low, days, high;
Tiered(int low, int days, int high) { this.low = low; this.days = days; this.high = high; }
public int fine(int daysLate, int price) {
int first = Math.min(daysLate, days);
return Math.min(first * low + (daysLate - first) * high, price);
}
}
record Plan(String name, int maxLoans, int loanDays, int maxRenewals, FinePolicy fines) {}
static final Plan STUDENT = new Plan("student", 3, 14, 1, new PerDay(5, 200));
static final Plan FACULTY = new Plan("faculty", 10, 30, 3, new NoFine());
static final Plan PUBLIC = new Plan("public", 2, 14, 1, new Tiered(2, 7, 10));
static final int BLOCK_AT = 100; // rupees of unpaid fines that stop new loans
// ---------------- entities ----------------
static class Loan {
final int id; final String barcode, isbn, memberId; final int start, waited;
int due, renewals = 0; Integer returned = null;
Loan(int id, String barcode, String isbn, String memberId, int start, int due, int waited) {
this.id = id; this.barcode = barcode; this.isbn = isbn; this.memberId = memberId;
this.start = start; this.due = due; this.waited = waited;
}
}
static class Copy {
final String barcode, isbn; final int price;
Status status = Status.AVAILABLE;
String heldFor = null; int holdUntil = 0, holdSince = 0;
Loan loan = null;
Copy(String barcode, String isbn, int price) { this.barcode = barcode; this.isbn = isbn; this.price = price; }
void move(Status to) {
if (!ALLOWED.get(status).contains(to))
throw new AssertionError(barcode + ": " + status.label + " -> " + to.label);
status = to;
}
}
/** A title. Copies and the hold queue change together, so they share one lock (the Book itself). */
static class Book {
final String isbn, title, authors, subject;
final List<Copy> copies = new ArrayList<>();
final ArrayDeque<Object[]> holds = new ArrayDeque<>(); // {memberId, day placed}
Book(String isbn, String title, String authors, String subject) {
this.isbn = isbn; this.title = title; this.authors = authors; this.subject = subject;
}
}
static class Member {
final String id, name; final Plan plan;
final LinkedHashMap<String, Loan> loans = new LinkedHashMap<>(); // barcode -> open loan
int finesDue = 0;
Member(String id, String name, Plan plan) { this.id = id; this.name = name; this.plan = plan; }
}
static final Pattern WORD = Pattern.compile("[a-z0-9]+");
static List<String> words(String text) {
List<String> out = new ArrayList<>();
Matcher m = WORD.matcher(text.toLowerCase());
while (m.find()) out.add(m.group());
return out;
}
// ---------------- the service ----------------
// Lock order is always book, then member. Nothing takes them the other way round.
final int holdDays;
volatile int today = 1;
final LinkedHashMap<String, Book> books = new LinkedHashMap<>();
final Map<String, Copy> copies = new HashMap<>();
final LinkedHashMap<String, Member> members = new LinkedHashMap<>();
final Map<String, Set<String>> index = new HashMap<>();
final List<String> events = Collections.synchronizedList(new ArrayList<>());
private int nextLoan = 1;
private final Object idLock = new Object();
Library(int holdDays) { this.holdDays = holdDays; }
// catalog
void addBook(String isbn, String title, String authors, String subject) {
books.put(isbn, new Book(isbn, title, authors, subject));
for (String w : new HashSet<>(words(title + " " + authors + " " + subject)))
index.computeIfAbsent(w, k -> new HashSet<>()).add(isbn);
}
void addCopy(String isbn, String barcode, int price) {
Book book = books.get(isbn);
synchronized (book) {
Copy copy = new Copy(barcode, isbn, price);
book.copies.add(copy);
copies.put(barcode, copy);
if (!book.holds.isEmpty()) route(book, copy); // people were already waiting for this title
}
}
List<Book> search(String query) {
Set<String> hits = null;
for (String w : words(query)) {
Set<String> s = index.getOrDefault(w, Set.of());
if (hits == null) hits = new HashSet<>(s); else hits.retainAll(s);
}
List<Book> out = new ArrayList<>();
if (hits != null) for (String i : hits) out.add(books.get(i));
out.sort(Comparator.comparing(b -> b.title));
return out;
}
void register(String id, String name, Plan plan) { members.put(id, new Member(id, name, plan)); }
// borrowing
/** At the desk: the member is holding this exact copy. */
Loan checkout(String memberId, String barcode) {
Copy copy = copies.get(barcode);
Book book = books.get(copy.isbn);
Member m = members.get(memberId);
synchronized (book) {
synchronized (m) {
canBorrow(m);
if (copy.status == Status.ON_HOLD_SHELF && !m.id.equals(copy.heldFor))
throw new LibraryError(barcode + " is on the hold shelf for " + copy.heldFor);
if (copy.status != Status.AVAILABLE && copy.status != Status.ON_HOLD_SHELF)
throw new LibraryError(barcode + " is " + copy.status.label);
return lend(copy, m);
}
}
}
/** In the app: lend any copy if one is free, otherwise join the queue.
* Returns the Loan, or the member's position in the queue as an Integer. */
Object request(String memberId, String isbn) {
Book book = books.get(isbn);
Member m = members.get(memberId);
synchronized (book) {
synchronized (m) {
canBorrow(m);
for (Copy c : book.copies)
if (c.status == Status.ON_HOLD_SHELF && m.id.equals(c.heldFor)) return lend(c, m);
for (Loan l : m.loans.values())
if (l.isbn.equals(isbn)) throw new LibraryError(m.name + " already has " + book.title);
int pos = 1;
for (Object[] h : book.holds) {
if (h[0].equals(m.id))
throw new LibraryError(m.name + " is already number " + pos + " for " + book.title);
pos++;
}
for (Copy c : book.copies) if (c.status == Status.AVAILABLE) return lend(c, m);
book.holds.addLast(new Object[]{m.id, today});
return book.holds.size();
}
}
}
Loan renew(String barcode) {
Copy copy = copies.get(barcode);
Book book = books.get(copy.isbn);
synchronized (book) {
Loan loan = copy.loan;
if (loan == null) throw new LibraryError(barcode + " is not on loan");
Member m = members.get(loan.memberId);
synchronized (m) {
if (!book.holds.isEmpty())
throw new LibraryError(book.holds.size() + " waiting for " + book.title);
if (loan.renewals >= m.plan.maxRenewals())
throw new LibraryError("already renewed " + loan.renewals + " time(s)");
if (today > loan.due) throw new LibraryError("overdue since day " + loan.due);
loan.due = today + m.plan.loanDays();
loan.renewals++;
return loan;
}
}
}
/** Returns the fine charged, in rupees. */
int returnCopy(String barcode) {
Copy copy = copies.get(barcode);
Book book = books.get(copy.isbn);
synchronized (book) {
Loan loan = copy.loan;
if (loan == null) throw new LibraryError(barcode + " is not on loan");
Member m = members.get(loan.memberId);
synchronized (m) {
int fine = m.plan.fines().fine(Math.max(0, today - loan.due), copy.price);
m.finesDue += fine;
loan.returned = today;
m.loans.remove(barcode);
copy.loan = null;
route(book, copy);
return fine;
}
}
}
int reportLost(String barcode) {
Copy copy = copies.get(barcode);
Book book = books.get(copy.isbn);
synchronized (book) {
Loan loan = copy.loan;
if (loan == null) throw new LibraryError(barcode + " is not on loan");
Member m = members.get(loan.memberId);
synchronized (m) {
m.finesDue += copy.price;
loan.returned = today;
m.loans.remove(barcode);
copy.loan = null;
copy.move(Status.LOST);
return copy.price;
}
}
}
void pay(String memberId, int amount) {
Member m = members.get(memberId);
synchronized (m) {
if (!(0 < amount && amount <= m.finesDue))
throw new LibraryError(m.name + " owes Rs " + m.finesDue + ", cannot pay Rs " + amount);
m.finesDue -= amount;
}
}
/** Start a new day: copies nobody collected go to the next person. Returns how many expired. */
int advanceTo(int day) {
today = day;
int expired = 0;
for (Book book : books.values()) {
synchronized (book) {
for (Copy c : book.copies) {
if (c.status == Status.ON_HOLD_SHELF && c.holdUntil < day) {
expired++;
events.add("day " + day + ": " + c.barcode + " not collected by " + c.heldFor);
route(book, c);
}
}
}
}
return expired;
}
// internals: callers hold the book lock (and the member lock where a member is touched)
private void canBorrow(Member m) {
if (m.loans.size() >= m.plan.maxLoans())
throw new LibraryError(m.name + " has " + m.loans.size() + " books, the " + m.plan.name() + " limit");
if (m.finesDue >= BLOCK_AT) throw new LibraryError(m.name + " owes Rs " + m.finesDue + " in fines");
for (Loan l : m.loans.values())
if (l.due < today) throw new LibraryError(m.name + " has " + l.barcode + " overdue since day " + l.due);
}
private Loan lend(Copy copy, Member m) {
int waited = copy.status == Status.ON_HOLD_SHELF ? today - copy.holdSince : 0;
int loanId;
synchronized (idLock) { loanId = nextLoan++; }
Loan loan = new Loan(loanId, copy.barcode, copy.isbn, m.id, today, today + m.plan.loanDays(), waited);
copy.move(Status.ON_LOAN);
copy.heldFor = null;
copy.loan = loan;
m.loans.put(copy.barcode, loan);
return loan;
}
/** A copy is free: give it to the head of the queue, or put it back on the shelf. */
private void route(Book book, Copy copy) {
if (!book.holds.isEmpty()) {
Object[] h = book.holds.pollFirst();
copy.move(Status.ON_HOLD_SHELF);
copy.heldFor = (String) h[0];
copy.holdSince = (Integer) h[1];
copy.holdUntil = today + holdDays;
events.add("day " + today + ": " + copy.barcode + " held for " + copy.heldFor + " until day " + copy.holdUntil);
} else {
copy.heldFor = null;
copy.move(Status.AVAILABLE);
}
}
// ---------------- demo ----------------
static void attempt(String label, Supplier<Object> fn) {
try {
Object r = fn.get();
if (r instanceof Loan l) System.out.println(" " + label + ": loan #" + l.id + ", due day " + l.due);
else if (r instanceof Integer i && label.contains("request"))
System.out.println(" " + label + ": queued, position " + i);
else System.out.println(" " + label + ": ok" + (r == null ? "" : ", " + r));
} catch (LibraryError e) {
System.out.println(" " + label + ": refused: " + e.getMessage());
}
}
static void flush(Library lib) {
for (String e : lib.events) System.out.println(" event " + e);
lib.events.clear();
}
static Library build() {
Library lib = new Library(3);
lib.addBook("EJ", "Effective Java", "Joshua Bloch", "java");
lib.addBook("DP", "Design Patterns", "Gamma Helm Johnson Vlissides", "software design");
lib.addBook("DD", "Designing Data-Intensive Applications", "Martin Kleppmann", "databases");
lib.addBook("CC", "Clean Code", "Robert C. Martin", "software design");
Object[][] stock = {{"EJ", 2, 899}, {"DP", 1, 1050}, {"DD", 3, 1850}, {"CC", 1, 650}};
for (Object[] s : stock)
for (int i = 1; i <= (Integer) s[1]; i++) lib.addCopy((String) s[0], s[0] + "-" + i, (Integer) s[2]);
lib.register("aman", "Aman", STUDENT);
lib.register("bela", "Bela", STUDENT);
lib.register("chirag", "Chirag", FACULTY);
lib.register("divya", "Divya", PUBLIC);
return lib;
}
static Supplier<Object> fine(Supplier<Integer> f, String word) { return () -> word + " Rs " + f.get(); }
public static void main(String[] args) throws Exception {
Library lib = build();
System.out.println("1) Search is exact words over title, author and subject");
for (String q : List.of("design", "martin", "data intensive", "designs")) {
StringJoiner shown = new StringJoiner(", ");
for (Book b : lib.search(q)) {
long avail = b.copies.stream().filter(c -> c.status == Status.AVAILABLE).count();
shown.add(b.title + " (" + avail + "/" + b.copies.size() + ")");
}
System.out.println(" " + String.format("%-17s", "'" + q + "'") + " -> "
+ (shown.length() == 0 ? "nothing" : shown.toString()));
}
System.out.println("\n2) Plan limits, day 1");
attempt("aman checkout EJ-1", () -> lib.checkout("aman", "EJ-1"));
attempt("aman checkout DD-1", () -> lib.checkout("aman", "DD-1"));
attempt("aman checkout CC-1", () -> lib.checkout("aman", "CC-1"));
attempt("aman checkout EJ-2", () -> lib.checkout("aman", "EJ-2"));
attempt("chirag checkout DP-1", () -> lib.checkout("chirag", "DP-1"));
attempt("chirag checkout EJ-1", () -> lib.checkout("chirag", "EJ-1"));
System.out.println("\n3) Days 2-27: one copy of Design Patterns, two people waiting");
lib.advanceTo(2);
attempt("bela request DP", () -> lib.request("bela", "DP"));
attempt("divya request DP", () -> lib.request("divya", "DP"));
attempt("bela request DP", () -> lib.request("bela", "DP"));
attempt("bela request EJ", () -> lib.request("bela", "EJ"));
lib.advanceTo(14);
attempt("aman renew CC-1 (day 14)", () -> lib.renew("CC-1"));
lib.advanceTo(20);
attempt("chirag renew DP-1 (day 20)", () -> lib.renew("DP-1"));
lib.advanceTo(22);
attempt("chirag return DP-1 (day 22)", fine(() -> lib.returnCopy("DP-1"), "fine"));
flush(lib);
attempt("divya checkout DP-1", () -> lib.checkout("divya", "DP-1"));
attempt("bela checkout DP-1", () -> lib.checkout("bela", "DP-1"));
lib.advanceTo(26);
flush(lib);
lib.advanceTo(27);
attempt("divya request DP (day 27)", () -> lib.request("divya", "DP"));
attempt("aman renew CC-1 (day 27)", () -> lib.renew("CC-1"));
System.out.println("\n4) Days 29-75: fines");
lib.advanceTo(29);
attempt("aman return EJ-1 (day 29)", fine(() -> lib.returnCopy("EJ-1"), "fine"));
attempt("aman return DD-1 (day 29)", fine(() -> lib.returnCopy("DD-1"), "fine"));
lib.advanceTo(52);
attempt("divya return DP-1 (day 52)", fine(() -> lib.returnCopy("DP-1"), "fine"));
lib.advanceTo(75);
attempt("aman return CC-1 (day 75)", fine(() -> lib.returnCopy("CC-1"), "fine"));
attempt("bela return EJ-2 (day 75)", fine(() -> lib.returnCopy("EJ-2"), "fine"));
attempt("aman checkout DD-1", () -> lib.checkout("aman", "DD-1"));
attempt("aman pay Rs 500", () -> { lib.pay("aman", 500); return null; });
attempt("aman pay Rs 300", () -> { lib.pay("aman", 300); return null; });
attempt("aman checkout DD-1", () -> lib.checkout("aman", "DD-1"));
System.out.println(" aman still owes Rs " + lib.members.get("aman").finesDue + ", under the Rs " + BLOCK_AT + " block");
System.out.println("\n5) A lost copy is charged at its price and leaves circulation");
attempt("aman reports DD-1 lost", fine(() -> lib.reportLost("DD-1"), "charged"));
attempt("chirag checkout DD-1", () -> lib.checkout("chirag", "DD-1"));
StringJoiner dd = new StringJoiner(", ");
for (Copy c : lib.books.get("DD").copies) dd.add(c.barcode + " " + c.status.label);
System.out.println(" DD copies: " + dd);
System.out.println("\n6) Eight members request 3 copies at the same moment");
lib.addBook("PP", "The Pragmatic Programmer", "David Thomas Andrew Hunt", "software craft");
for (int i = 1; i <= 3; i++) lib.addCopy("PP", "PP-" + i, 700);
for (int i = 1; i <= 8; i++) lib.register("m" + i, "M" + i, STUDENT);
List<Object> results = Collections.synchronizedList(new ArrayList<>());
CyclicBarrier start = new CyclicBarrier(8);
List<Thread> threads = new ArrayList<>();
for (int i = 1; i <= 8; i++) {
String mid = "m" + i;
threads.add(new Thread(() -> {
try { start.await(); } catch (Exception e) { throw new RuntimeException(e); }
results.add(lib.request(mid, "PP"));
}));
}
for (Thread t : threads) t.start();
for (Thread t : threads) t.join();
Set<Integer> ids = new HashSet<>();
List<Integer> positions = new ArrayList<>();
int loans = 0;
for (Object r : results) {
if (r instanceof Loan l) { loans++; ids.add(l.id); } else positions.add((Integer) r);
}
Collections.sort(positions);
Book pp = lib.books.get("PP");
long onLoan = pp.copies.stream().filter(c -> c.status == Status.ON_LOAN).count();
System.out.println(" loans: " + loans + ", loan ids distinct: " + (ids.size() == loans ? "True" : "False"));
System.out.println(" queue positions handed out: " + positions + ", queue length: " + pp.holds.size());
System.out.println(" copies on loan: " + onLoan);
System.out.println("\n7) One simulated year, 120 members, 40 titles: hold shelf 3 days vs 7 days");
simulate(3);
simulate(7);
}
// ---------------- simulation ----------------
static class Lcg {
long s;
Lcg(long seed) { s = seed; }
int next(int n) {
s = s * 6364136223846793005L + 1442695040888963407L;
return (int) ((s >>> 33) % n);
}
}
static String tenths(long num, long den) {
if (den == 0) return "n/a";
long t = num * 10 / den;
return (t / 10) + "." + (t % 10);
}
static void simulate(int holdDays) {
Lcg rnd = new Lcg(2026);
Library lib = new Library(holdDays);
for (int t = 0; t < 40; t++) {
String isbn = String.format("T%02d", t);
lib.addBook(isbn, "Title " + isbn.substring(1), "Author", "subject");
int n = 1 + rnd.next(3);
for (int c = 0; c < n; c++) lib.addCopy(isbn, isbn + "-" + (c + 1), 300 + 100 * rnd.next(15));
}
for (int i = 0; i < 120; i++) {
Plan plan = i % 10 == 0 ? FACULTY : i % 5 == 1 ? PUBLIC : STUDENT;
String id = String.format("u%03d", i);
lib.register(id, id, plan);
}
Map<Integer, Integer> planned = new HashMap<>(); // loan id -> day the member brings it back
long loansN = 0, late = 0, fines = 0, renewOk = 0, renewWaiting = 0, queued = 0, collected = 0,
waited = 0, expired = 0, shelfDays = 0, longest = 0, refLimit = 0, refFines = 0, refOverdue = 0;
for (int day = 1; day <= 365; day++) {
expired += lib.advanceTo(day);
lib.events.clear();
for (Member m : lib.members.values()) {
List<Loan> open = new ArrayList<>(m.loans.values());
open.sort(Comparator.comparingInt(l -> l.id));
for (Loan loan : open) {
if (day == loan.due && planned.get(loan.id) > loan.due) {
try { lib.renew(loan.barcode); renewOk++; }
catch (LibraryError e) { if (e.getMessage().contains("waiting")) renewWaiting++; }
}
if (planned.get(loan.id) == day) {
int f = lib.returnCopy(loan.barcode);
if (loan.returned > loan.due) late++;
fines += f;
}
}
List<Copy> held = new ArrayList<>();
for (Book b : lib.books.values())
for (Copy c : b.copies)
if (c.status == Status.ON_HOLD_SHELF && m.id.equals(c.heldFor)) held.add(c);
String want = null;
if (!held.isEmpty() && rnd.next(10) < 3) want = held.get(0).isbn;
else if (rnd.next(100) < 3) want = String.format("T%02d", Math.min(rnd.next(40), rnd.next(40)));
if (want == null) continue;
Object r;
try {
r = lib.request(m.id, want);
} catch (LibraryError e) {
String msg = e.getMessage();
if (msg.contains("limit")) refLimit++;
else if (msg.contains("fines")) { refFines++; lib.pay(m.id, m.finesDue); }
else if (msg.contains("overdue")) refOverdue++;
continue;
}
if (r instanceof Loan l) {
loansN++;
if (l.waited != 0) { collected++; waited += l.waited; }
int x = rnd.next(100), ret;
if (x < 70) ret = l.start + 1 + rnd.next(l.due - l.start);
else if (x < 90) ret = l.due + 1 + rnd.next(7);
else ret = l.due + 8 + rnd.next(30);
planned.put(l.id, ret);
} else {
queued++;
longest = Math.max(longest, (Integer) r);
}
}
for (Book b : lib.books.values())
for (Copy c : b.copies) if (c.status == Status.ON_HOLD_SHELF) shelfDays++;
}
System.out.println(" hold shelf " + holdDays + " days:");
System.out.println(" loans " + loansN + ", returned late " + late + ", fines Rs " + fines);
System.out.println(" renewals ok " + renewOk + ", refused because someone was waiting " + renewWaiting);
System.out.println(" joined a queue " + queued + ", longest queue " + longest);
System.out.println(" holds collected " + collected + ", expired " + expired
+ ", average wait " + tenths(waited, collected) + " days");
System.out.println(" copy-days spent on the hold shelf " + shelfDays);
System.out.println(" refused: at limit " + refLimit + ", fines " + refFines + ", overdue book " + refOverdue);
}
}
What it printed
1) Search is exact words over title, author and subject
'design' -> Clean Code (1/1), Design Patterns (1/1)
'martin' -> Clean Code (1/1), Designing Data-Intensive Applications (3/3)
'data intensive' -> Designing Data-Intensive Applications (3/3)
'designs' -> nothing
2) Plan limits, day 1
aman checkout EJ-1: loan #1, due day 15
aman checkout DD-1: loan #2, due day 15
aman checkout CC-1: loan #3, due day 15
aman checkout EJ-2: refused: Aman has 3 books, the student limit
chirag checkout DP-1: loan #4, due day 31
chirag checkout EJ-1: refused: EJ-1 is on loan
3) Days 2-27: one copy of Design Patterns, two people waiting
bela request DP: queued, position 1
divya request DP: queued, position 2
bela request DP: refused: Bela is already number 1 for Design Patterns
bela request EJ: loan #5, due day 16
aman renew CC-1 (day 14): loan #3, due day 28
chirag renew DP-1 (day 20): refused: 2 waiting for Design Patterns
chirag return DP-1 (day 22): ok, fine Rs 0
event day 22: DP-1 held for bela until day 25
divya checkout DP-1: refused: DP-1 is on the hold shelf for bela
bela checkout DP-1: refused: Bela has EJ-2 overdue since day 16
event day 26: DP-1 not collected by bela
event day 26: DP-1 held for divya until day 29
divya request DP (day 27): loan #6, due day 41
aman renew CC-1 (day 27): refused: already renewed 1 time(s)
4) Days 29-75: fines
aman return EJ-1 (day 29): ok, fine Rs 70
aman return DD-1 (day 29): ok, fine Rs 70
divya return DP-1 (day 52): ok, fine Rs 54
aman return CC-1 (day 75): ok, fine Rs 200
bela return EJ-2 (day 75): ok, fine Rs 200
aman checkout DD-1: refused: Aman owes Rs 340 in fines
aman pay Rs 500: refused: Aman owes Rs 340, cannot pay Rs 500
aman pay Rs 300: ok
aman checkout DD-1: loan #7, due day 89
aman still owes Rs 40, under the Rs 100 block
5) A lost copy is charged at its price and leaves circulation
aman reports DD-1 lost: ok, charged Rs 1850
chirag checkout DD-1: refused: DD-1 is lost
DD copies: DD-1 lost, DD-2 available, DD-3 available
6) Eight members request 3 copies at the same moment
loans: 3, loan ids distinct: True
queue positions handed out: [1, 2, 3, 4, 5], queue length: 5
copies on loan: 3
7) One simulated year, 120 members, 40 titles: hold shelf 3 days vs 7 days
hold shelf 3 days:
loans 938, returned late 127, fines Rs 5186
renewals ok 147, refused because someone was waiting 118
joined a queue 585, longest queue 22
holds collected 339, expired 141, average wait 34.0 days
copy-days spent on the hold shelf 1018
refused: at limit 2, fines 24, overdue book 41
hold shelf 7 days:
loans 903, returned late 168, fines Rs 9721
renewals ok 132, refused because someone was waiting 152
joined a queue 637, longest queue 30
holds collected 414, expired 57, average wait 43.4 days
copy-days spent on the hold shelf 1436
refused: at limit 4, fines 44, overdue book 96
Reading it:
- Demo 1. “design” finds Design Patterns by title and Clean Code by subject, but not Designing Data-Intensive Applications, and “designs” finds nothing. That is exact-word search. Real catalogues stem words (“designing” and “designs” both become “design”) or hand search to Elasticsearch. “martin” finds both Robert C. Martin and Martin Kleppmann, which is correct.
- Demo 2. Aman’s fourth book is refused at the student limit.
EJ-1is already on loan to Aman, so Chirag cannot take it at the desk. - Demo 3. Bela and Divya queue for the one copy. Bela’s second request is refused with her position. Her request for Effective Java is not a hold at all, because
EJ-2is on the shelf. Chirag cannot renew with two people waiting. He returnsDP-1on day 22, the copy goes to the hold shelf for Bela until day 25, and the desk refuses it to Divya. Bela cannot collect it either: herEJ-2was due on day 16. On day 26 the hold expires and the copy passes to Divya, who collects it on day 27. Aman’s first renewal (day 14) moves his due date to 28; his second is refused. - Demo 4.
EJ-1andDD-1were due on day 15 and come back on day 29: 14 days × ₹5 = ₹70 each. Divya’sDP-1was due on day 41 and comes back on day 52: 7 × ₹2 + 4 × ₹10 = ₹54.CC-1is 47 days late, ₹235, capped at ₹200, and so is Bela’sEJ-2(59 days). Aman owes ₹340 and is blocked; an overpayment is refused; after paying ₹300 he owes ₹40, which is under the ₹100 block, so he can borrow again. - Demo 5. A lost copy charges ₹1,850 and leaves circulation for good; the other two copies are unaffected.
- Demo 6. 8 simultaneous requests for 3 copies: 3 loans with distinct ids, positions 1 to 5 handed out once each, 5 people in the queue.
What the simulated year says
Demo 7 runs the same library for 365 days twice, with a 3-day and a 7-day hold shelf. One run can mislead, because once the first hold expires differently the two random streams go different ways. So I also ran it with 20 different seeds and averaged:
| Per year, average of 20 seeds | 3-day shelf | 7-day shelf |
|---|---|---|
| Holds that expired uncollected | 154 | 47 |
| Holds collected | 347 | 446 |
| Copy-days spent on the hold shelf | 1,086 | 1,392 |
| Average wait from hold to collection | 31.9 days | 41.9 days |
| Loans | 935 | 971 |
| Renewals refused because someone was waiting | 135 | 155 |
The 7-day shelf cuts expired holds by about 70% and lets about 100 more people a year get the book they queued for. The cost is about 300 more copy-days of books sitting on a trolley, close to one copy permanently out of circulation, and the average wait from hold to collection goes up by ten days. Neither is “correct”. A university library during exams wants the short window; a public library with patrons who come in on weekends wants the long one. That is why hold_days is a constructor argument and not a constant, and it is a better thing to say in an interview than “holds expire after 3 days”.
The other number worth noticing: about one renewal in two is refused because someone is waiting. On a popular title, renewals and holds are the same resource, and a rule that renewals beat holds would make queues effectively endless.
Where interviewers take it next
“Several branches.” A copy gets a home_branch and a current_branch, and a new state, IN_TRANSIT. The hold queue stays per title across the whole system, but a held copy is routed to the branch the member chose for pickup, and the hold-shelf clock starts when it arrives, not when it is returned. Search shows availability per branch.
“Reserve a specific edition, or any edition.” Add a Work above Book: Effective Java is one work with three editions (three ISBNs). A hold on the work is satisfied by any edition’s copy; a hold on an ISBN only by that edition. The queue moves up a level for “any edition” holds, and _route has to check both queues, oldest first.
“Show the member where they are in the queue and an estimated date.” Position is the index in the deque. An estimate needs the due dates of the copies on loan and the hold window, and it is honest to show a range: a renewal or an uncollected hold moves it by weeks.
“A librarian marks a returned copy as damaged.” Another state, IN_REPAIR, reachable from ON_LOAN and leading back through _route. Adding it is one row in the transition table, which is the payoff for writing the table.
“Store it in a database.” Tables title, copy, member, loan, hold (title_id, member_id, placed_at, position), fine. The hold queue becomes ORDER BY placed_at, id. The nightly advance_to becomes a scheduled job with WHERE status='ON_HOLD_SHELF' AND hold_until < today. Keep the fine as a row written at return time, not a view.
“Two librarians scan the same returned copy at once.” The second return_copy finds no open loan and is refused. In a database, the return is UPDATE loan SET returned_at=now() WHERE id=? AND returned_at IS NULL, and a zero row count means someone else already did it.
Mistakes worth avoiding
- One
Bookclass with anisIssuedflag. There is nowhere to put the second copy, and nowhere to put a queue. - A hold on a specific copy. The first copy back should go to the first person waiting, whichever copy it is.
datetime.now()inside the model. The demo above needs days 1, 14, 22, 26 and 75 in one run. With a wall clock you cannot test expiry or fines without waiting.- Recomputing fines from today’s date on every view. Fines change after they are paid, and a policy change rewrites history.
- Letting renewals ignore the queue. A borrower who renews forever keeps a popular book out of reach for everyone else.
- Several code paths that free a copy. Return, expiry and new stock must all go through one routing function, or one of them will forget the queue.
- Locks in different orders.
return_copylocking member then book whilerequestlocks book then member will deadlock, rarely and under load. Student extends Member. The plan is data.
Key takeaways
- Separate the title (
Book) from the physical copy (Copy); loans link a copy to a member. - Holds queue on the title. One routing function decides where every freed copy goes.
- A copy’s states and legal moves fit in an eight-row table; illegal moves are bugs and should fail loudly.
- Fines are a strategy computed once at return; member types are plans, not subclasses.
- Pass time in. A day number makes holds, renewals and fines testable.
- Lock per title, then member, always in that order. Without the lock, 4% of simulated races lent one copy to two people.
Exercises
- Add
IN_REPAIR. Which rows of the transition table change, and which methods need no change at all? - Add multi-branch pickup: a hold records a pickup branch, and a copy returned at another branch spends one day
IN_TRANSITbefore the hold-shelf clock starts. Rerun demo 3 with Divya picking up at a different branch. - Allow a renewal while people are waiting if the title has more copies than people in its queue. Rerun demo 7 with both hold windows: what happens to refused renewals and to the average wait?
- Replace exact-word search with prefix search (a sorted list of words and
bisect, or a trie). Does “design” now find Designing Data-Intensive Applications? Does “data” find anything new it should not?
Quiz
- Why is the hold queue on the title and not on the copy?
- A public member returns a ₹650 book 30 days late. What is the fine under the tiered policy?
- Why does
requestlook for a copy held for this member before looking for an available one? - A renewal on day 3 of a 14-day loan. What is the new due date, and why not 28 days after the loan started?
return_copyneeds the member’s lock as well as the title’s. In what order does it take them, and what goes wrong if one method takes them the other way?
Show answers
- People want the title. With a queue per copy, a different copy that comes back first goes to the open shelf (or to someone who queued later on that copy) while the first person keeps waiting.
- 7 × ₹2 + 23 × ₹10 = ₹244. The cap is the book’s price, ₹650, so ₹244.
- If a copy is already reserved on the hold shelf for them and they take a different, free copy, the reserved one sits there until it expires and is passed on late. Giving them the held copy frees the other for the next person.
- Day 3 + 14 = day 17. Extending from the due date would turn an early renewal into a free 28-day loan.
- Book first, then member, the same as every other method. If one method took member then book while another took book then member, two threads could each hold one lock and wait for the other forever.