Notes
Requirements
The requirements. The catalogue holds books, and each book has several physical copies. Members search by words in the title or author. Members are students or faculty, each plan with its own loan limit and loan period. Members borrow and return copies, reserve a book when every copy is out, pay a fine per late day up to a cap, and cannot borrow while they owe money. They are notified when a reserved copy is ready.
Clarify holds and fines, because they carry the edge cases. A member reserves a title, not a specific copy. The queue is first come, first served. When a copy comes back and someone is waiting, it goes on hold for the first person in line, and nobody else can take it. Fines are per late day with a cap per loan, so one forgotten book does not become a fortune.
- catalogue of books, many copies
- search by title or author words
- members: student or faculty
- with a loan limit and period
- borrow and return copies
- reserve when no copy is free
- fine per late day, capped
- no borrowing with unpaid fines
- notify when a hold is ready
- out of scope: e-books, payments
- reserve a title or a copy?
- a title, any copy will do
- hold queue order?
- first come, first served
- returned copy with a queue?
- held for the first in line
- can others take a held copy?
- no
- fine cap?
- yes, 200.00 per loan
Entities
The entities, and the one distinction that matters. A book is the catalogue entry: ISBN, title, author, year. A copy is a physical item with a barcode and a status. Three copies of one book share one book record. Group everything about one book, its copies and its waiting list, into a title. A loan ties one copy to one member with a due date. Mixing up book and copy is the most common modelling mistake here.
Class diagram
In code, a book and a loan are records, because they never change. A copy has a status, available, borrowed, on hold or lost, and who it is held for. A member has a plan, a count of active loans and unpaid fines. A title holds the book, its copies and a first in, first out queue of members waiting. Money is a long count of paise.
record Book(isbn, title, author, year)
enum CopyStatus { AVAILABLE, BORROWED,
ON_HOLD, LOST }
class Copy { barcode, book, status,
heldFor }
class Member { id, name, plan,
activeLoans, unpaidFines }
record Loan(id, copy, member,
borrowed, due)
class Title { book, copies, holds } Plans as data
Membership rules are data. Each plan is an enum constant carrying its loan limit and loan period: students may hold two books for fourteen days, faculty ten for sixty. The borrow code reads the member's plan instead of asking if this is a student. Adding a staff or guest plan is one new line, and nothing else changes. Interviewers like seeing rules moved out of conditionals.
enum Plan {
STUDENT(2, 14), FACULTY(10, 60);
final int maxLoans;
final int loanDays;
}
borrow: activeLoans >= maxLoans? no
due = now + plan.loanDays
new plan (staff, guest): one line Search
Search uses an inverted index. When a copy is added, every word of its title and author maps to its ISBN. A query looks up each word and intersects the sets, so all words must match. Results show how many copies are on the shelf right now. Systems finds two books; author two finds one. For prefix or fuzzy search, use a trie, or in production a search engine, but the idea is the same.
on addCopy: for each word in title + author: index[word].add(isbn) search: hits = index[word1] retainAll(index[word2]) ... show title + copies on the shelf "systems": Designing Data Systems (2/2), Systems Design Primer (1/1) prefix search: a trie or sorted map
Flow: borrow
Borrowing. Lock the member and check the rules: no unpaid fines, and under the plan's limit. Then lock the title and pick a copy: one already on hold for this member wins, otherwise any copy on the shelf, unless other people are queued ahead. Mark the copy borrowed, count the loan, and create the loan with a due date from the plan and an injected clock.
synchronized (member) {
if unpaidFines > 0: throw
if activeLoans >= plan.max: throw
synchronized (title) {
copy = pickCopy(title, member)
copy.status = BORROWED
activeLoans++
return new Loan(.., now + days)
}
} Lock ordering
Two operations need two locks each, the member and the title, and that is where deadlocks come from. If borrow took the member then the title, while return took the title then the member, each could hold one lock and wait forever for the other. The fix is a single global order: always member first, then title, in every method. With one order, a cycle of waiting is impossible. Saying this unprompted is a strong signal.
- borrow: member, then title
- return: member, then title
- if return took title first:
- borrow holds M, wants T
- return holds T, wants M
- both wait forever
- one global order = no cycle
Flow: reserve
Reserving. Both copies are out, so faculty joins the queue for that title. If a copy is on the shelf, reserving makes no sense, so it is refused with a hint to just borrow it. Joining twice is ignored, and the member is told their position. The queue is a double-ended queue used first in, first out. Hold expiry, say three days to collect, is a natural follow-up.
synchronized (title) {
if (available() > 0)
throw: a copy is on the shelf
if (!holds.contains(m))
holds.addLast(m)
return holds.size()
}
holds: ArrayDeque, first in first out Flow: return
Returning. Remove the loan first, so a copy cannot be returned twice. Work out the late days and the fine. Then, under the member lock and the title lock in the same order as borrow, reduce the loan count, add the fine, and look at the queue. If someone is waiting, the copy goes on hold for them; otherwise it goes back on the shelf. Notify the next member after releasing the locks.
loan = loans.remove(barcode)
late = days(due, now), fine = f(late)
synchronized (member) {
activeLoans--, unpaidFines += fine
synchronized (title) {
next = holds.pollFirst()
copy: next == null ? AVAILABLE
: ON_HOLD(next)
}
}
notify next, outside the locks Strategy: fines
Fines are a strategy with one method: given late days, how much. Our default charges ten per day up to a cap of two hundred, so three days late is thirty. A grace period, skipping closed days, or a higher rate for rare books are new implementations. The member then cannot borrow until the fine is paid, which the demo checks.
interface FinePolicy {
long fine(long lateDays);
}
record PerDayFine(long perDay, long cap)
min(lateDays x perDay, cap)
3 days late x 10.00 = 30.00
grace days, weekends free,
rare books cost more: new classes Observer
Notifications are observers. When a returned copy goes on hold, the library tells every listener: email, a text message, the screen at the desk. Due soon and overdue reminders come from a daily scan of loans and use the same mechanism. Listeners are called after the locks are released, so a slow email service can never hold up the circulation desk.
interface LibraryListener {
void onHoldReady(Member m, Copy c);
}
email, SMS, the desk screen
later: onDueSoon, onOverdue
from a daily scheduled scan
called outside the locks Concurrency
Now the race. Eight members try to borrow the last two copies of one title at the same moment. Picking a copy and marking it borrowed happen under the title lock, so exactly two succeed and six are told there is no copy, every time. Member state is guarded by the member lock, always taken first. Titles, loans and the index live in concurrent maps, and removing the loan first makes a double return impossible.
- member state: member lock
- copies + holds: title lock
- order: member, then title
- titles, loans, index:
- ConcurrentHashMap
- loan removed first on return
- listeners: CopyOnWriteArrayList
- 8 racers, 2 copies: 2 loans
Extensibility
Extensions. A hold expires after three days and passes to the next in line. Renewal extends the due date only when nobody is waiting. A lost copy is a status plus a replacement charge. Several branches give each copy a location and allow transfers. E-books swap physical copies for a licence count. And an append-only history of loans supports reports and disputes.
- hold expiry: collect in 3 days
- or pass to the next in line
- renewals: extend due if no queue
- lost copy: status LOST + charge
- branches: Copy gets a location,
- transfers between branches
- e-books: a licence count
- instead of physical copies
- audit: append-only loan history
Testing
The full code is below the player. The demo searches the catalogue, lends both copies of one book, puts faculty in the queue, moves an injected clock seventeen days ahead, returns three days late for a fine of thirty and hands the copy to faculty with a notification. It blocks borrowing until the fine is paid, enforces the student limit, and races eight members for two copies.
Rejected: no copy of Designing Data Systems for Faculty Faculty joins the queue at position 1 [notify Faculty] Designing Data Systems is held for you at the desk Returned D-1: 3 days late, fine 30.00, copy goes to Faculty Rejected: Student has unpaid fines Rejected: Student reached the limit of 2 Race for 2 copies: 2 borrowed, 6 missed
Follow-ups
Expect follow-ups. Why separate book and copy? Search and holds are per book, but loans and status are per copy. How do you avoid deadlock? One lock order everywhere. What if a held copy is never collected? A scheduled job expires the hold and moves on. Search at scale uses a search engine with the same inverted index idea. In a database, lock the copy row and allow one active loan per copy.
- why separate Book and Copy?
- how do you avoid deadlock?
- held copy never collected?
- expiry job, next in line
- search at scale?
- a search engine, same index idea
- in a database?
- row lock on the copy, unique
- active loan per copy
Say it like this
The short version. A book is the catalogue entry and a copy is the physical item. A title groups the copies and a first in, first out hold queue under one lock. Borrow and return always lock the member, then the title. Plans are data, fines are a strategy, search is an inverted index, and hold notices go to observers.
- "A Book is the catalogue entry,
- a Copy is the physical item.
- A Title groups copies and a FIFO
- hold queue under one lock.
- Borrow and return lock member
- then title. Plans are data,
- fines a strategy, search an
- inverted index, notices
- observers."