Implement and test catalog service
What you will learn
Implement the reservation use case before mapping it to HTTP. The local reference serializes changes within one JVM. PostgreSQL must instead protect durable state and the command ledger in a transaction; a Java monitor cannot coordinate separate application replicas.
- Test accepted and rejected reservations.
- Explain idempotency and transaction boundaries.
- Map domain results to a typed HTTP contract.
Plain Java 21: save each example as Main.java in a fresh directory, compile with javac --release 21 Main.java, then run java Main. Trusted local fixtures only. No network or third-party dependency is needed.
Reject without mutating stock
public class Main { static class Stock { private int available=5; synchronized boolean reserve(int n){if(n<1||n>100)throw new IllegalArgumentException("quantity"); if(n>available)return false; available-=n;return true;} synchronized int available(){return available;} } public static void main(String[] args) throws Exception { var s=new Stock();System.out.println(s.reserve(3));System.out.println(s.reserve(3));System.out.println(s.available()); }}Expected output:
truefalse2A rejected reservation has no stock effect. This is a local monitor, not a database transaction.
HTTP contract
GET /catalog/{sku} returns 200 with a typed stock result or 404 for absent or out-of-tenant resource. POST /reservations accepts a validated SKU, quantity and command ID, returns 200 for applied or replayed success, 409 for insufficient stock or conflicting command identity, 400 for malformed input and 401 for missing authentication. The local adapter also returns 415 for an unsupported media type and 503 when its bounded command ledger is full. For the tiny local adapter, POST uses a deliberately narrow application/x-www-form-urlencoded grammar; the staged Spring adapter uses JSON DTOs. Test them independently rather than claiming wire-level equivalence. IDs and quantities have explicit bounds. Real public APIs need HTTPS, trusted token validation and robust JSON handling.
Atomic transaction and replay
The Spring design claims a command row under a tenant-scoped unique key. Within the same transaction, acquire the row, compare the request, conditionally UPDATE stock WHERE available >= requested, and store the result. A repeated command returns the saved result. A failed transaction rolls back both effects. The migration uses constraints and a foreign key; the conditional update prevents negative stock, including concurrent reservations. Test actual PostgreSQL under competing requests and failure between writes; the local synchronized model alone does not establish this.
Tests and negative paths
Run domain tests for empty and invalid IDs, quantity bounds, unknown items, duplicate requests, conflicting reuse, concurrent competing reservations and rejected updates. Then test the HTTP adapter on a loopback ephemeral port. The companion verifier compiles and packages the local solution, sends real HTTP requests, checks exact JSON and runs bounded concurrency. Framework and database execution are separate gates.
Model a replay ledger
public class Main { public static void main(String[] args) throws Exception { var ledger=new java.util.HashMap<String,Integer>(); System.out.println(ledger.putIfAbsent("R1",3)==null); System.out.println(ledger.putIfAbsent("R1",3)); }}Expected output:
true3The ledger model recognizes repeated identity. Full correctness also compares payload and atomically saves the outcome.
Map a typed result to a status
public class Main { enum Result { ACCEPTED, NOT_FOUND, CONFLICT } static int status(Result r){return switch(r){case ACCEPTED -> 200;case NOT_FOUND -> 404;case CONFLICT -> 409;};} public static void main(String[] args) throws Exception { System.out.println(status(Result.ACCEPTED)); System.out.println(status(Result.CONFLICT)); }}Expected output:
200409Typed domain outcomes keep transport decisions explicit.
Common mistakes
Do not retry with a new command ID after an ambiguous response. Do not equate synchronized with distributed locking or use a SELECT then unprotected UPDATE to enforce stock.
Practice
Start stock at five, reserve five, then reject one. Print true, false and zero.
Expected output:
truefalse0Compare with the manual review criteria.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Implement and test catalog service — knowledge check
Java enterprise capstone reasoning.
Why persist a command ID?
Where must the durable ledger and stock update commit?
What status represents conflicting command reuse?
What does a conditional UPDATE protect?
What does local synchronized evidence establish?