diff --git a/.github/scripts/verify-concept.sh b/.github/scripts/verify-concept.sh
index f241799..e35292d 100755
--- a/.github/scripts/verify-concept.sh
+++ b/.github/scripts/verify-concept.sh
@@ -8,32 +8,35 @@ set -uo pipefail
project="$1"; start_pass="$2"; total="$3"
failed=0
+# Logs go to a private temp folder, so two runs from one checkout do not mix their output.
+logs="$(mktemp -d)"
+trap 'rm -rf "$logs"' EXIT
+
count() { grep -c -F "$1" "$2" || true; }
echo "== $project/start: expecting $start_pass of $total, and a failing exit code"
-(cd "$project/start" && ./check) > start.log 2>&1
+(cd "$project/start" && ./check) > "$logs/start.log" 2>&1
start_exit=$?
-pass=$(count "[PASS]" start.log); fail=$(count "[FAIL]" start.log)
+pass=$(count "[PASS]" "$logs/start.log"); fail=$(count "[FAIL]" "$logs/start.log")
echo " got $pass of $((pass + fail)), exit code $start_exit"
if [ "$pass" != "$start_pass" ] || [ "$((pass + fail))" != "$total" ] || [ "$start_exit" = "0" ]; then
- echo " WRONG. Output of ./check in start/:"; cat start.log; failed=1
+ echo " WRONG. Output of ./check in start/:"; cat "$logs/start.log"; failed=1
fi
echo "== $project/solution: expecting $total of $total, and exit code 0"
-(cd "$project/solution" && ./check) > solution.log 2>&1
+(cd "$project/solution" && ./check) > "$logs/solution.log" 2>&1
solution_exit=$?
-pass=$(count "[PASS]" solution.log); fail=$(count "[FAIL]" solution.log)
+pass=$(count "[PASS]" "$logs/solution.log"); fail=$(count "[FAIL]" "$logs/solution.log")
echo " got $pass of $((pass + fail)), exit code $solution_exit"
if [ "$pass" != "$total" ] || [ "$fail" != "0" ] || [ "$solution_exit" != "0" ]; then
- echo " WRONG. Output of ./check in solution/:"; cat solution.log; failed=1
+ echo " WRONG. Output of ./check in solution/:"; cat "$logs/solution.log"; failed=1
fi
echo "== $project/solution: ./mvnw verify"
-if (cd "$project/solution" && ./mvnw -B -q verify) > verify.log 2>&1; then
+if (cd "$project/solution" && ./mvnw -B -q verify) > "$logs/verify.log" 2>&1; then
echo " green"
else
- echo " FAILED:"; tail -n 80 verify.log; failed=1
+ echo " FAILED:"; tail -n 80 "$logs/verify.log"; failed=1
fi
-rm -f start.log solution.log verify.log
exit $failed
diff --git a/README.md b/README.md
index 484b4b7..026b47a 100644
--- a/README.md
+++ b/README.md
@@ -68,8 +68,8 @@ A collection of hands-on coding interview projects organized by language. Each p
> **Backend concepts:** [java/concepts/](java/concepts/) is a different kind of project: not a timed
> round, but one concept taught step by step. Each is broken first (you run it and watch the problem
> happen), has challenge tasks and a guided version, tests as acceptance criteria, and `start/` and
-> `solution/` folders side by side. There are eight so far, numbered in the suggested order from
-> `01-transactional` to `08-idempotency`: see the [list](java/concepts/README.md).
+> `solution/` folders side by side. There are eleven so far, numbered in the suggested order from
+> `01-transactional` to `11-pagination`: see the [list](java/concepts/README.md).
## Structure
@@ -97,7 +97,7 @@ interview-prep/
│ ├── karat-drills/
│ ├── secret-storage/
│ ├── concepts/
-│ │ └── junior-mid/ (01-transactional ... 08-idempotency)
+│ │ └── junior-mid/ (01-transactional ... 11-pagination)
│ ├── DELIVERY_HERO.md
│ └── KARAT.md
├── python/
diff --git a/java/concepts/README.md b/java/concepts/README.md
index a95bcb4..8385dfc 100644
--- a/java/concepts/README.md
+++ b/java/concepts/README.md
@@ -19,6 +19,9 @@ under [`java/`](../).
| 06 | Junior / mid | [Thread safety](junior-mid/06-thread-safety/) | 1,000 requests are answered, the counter says 915 |
| 07 | Junior / mid | [Locking](junior-mid/07-locking/) | Two buyers both get the last item in stock |
| 08 | Junior / mid | [Idempotency](junior-mid/08-idempotency/) | One payment is retried and the customer is charged twice |
+| 09 | Junior / mid | [Isolation levels](junior-mid/09-isolation-levels/) | A bank statement whose lines add up to 1000 and whose total says 1100 |
+| 10 | Junior / mid | [Constraints and races](junior-mid/10-constraints-and-races/) | Two signups with the same email both succeed |
+| 11 | Junior / mid | [Pagination](junior-mid/11-pagination/) | Page 5,000 reads 100,000 rows to return 20 |
The numbers are the suggested order. Each project stands on its own, so you can start anywhere.
diff --git a/java/concepts/ci-projects.json b/java/concepts/ci-projects.json
index 5bd5378..4d2e2a3 100644
--- a/java/concepts/ci-projects.json
+++ b/java/concepts/ci-projects.json
@@ -6,5 +6,8 @@
{ "path": "java/concepts/junior-mid/05-rest-and-error-handling", "startPass": 13, "total": 56 },
{ "path": "java/concepts/junior-mid/06-thread-safety", "startPass": 18, "total": 29 },
{ "path": "java/concepts/junior-mid/07-locking", "startPass": 7, "total": 18 },
- { "path": "java/concepts/junior-mid/08-idempotency", "startPass": 15, "total": 32 }
+ { "path": "java/concepts/junior-mid/08-idempotency", "startPass": 15, "total": 32 },
+ { "path": "java/concepts/junior-mid/09-isolation-levels", "startPass": 22, "total": 31 },
+ { "path": "java/concepts/junior-mid/10-constraints-and-races", "startPass": 19, "total": 35 },
+ { "path": "java/concepts/junior-mid/11-pagination", "startPass": 15, "total": 35 }
]
diff --git a/java/concepts/junior-mid/09-isolation-levels/INTERVIEW_TASKS.md b/java/concepts/junior-mid/09-isolation-levels/INTERVIEW_TASKS.md
new file mode 100644
index 0000000..3327d5d
--- /dev/null
+++ b/java/concepts/junior-mid/09-isolation-levels/INTERVIEW_TASKS.md
@@ -0,0 +1,318 @@
+# Interview Tasks — Isolation Levels
+
+> **In `start/`, `./check` FAILS on purpose: 22 of 31 checks pass.** Tasks 2, 4 and 6 turn the other
+> 9 green. Tasks 1, 3, 5, 7 and 8 are inspection tasks: you run things, look, and answer questions.
+
+Do the tasks in order. Every fix is followed by an inspection task: a green test tells you the fix
+works, the inspection tells you **why**, and the why is what an interviewer asks for.
+
+Stuck, or want the explanation? The same task number in [`TASKS_GUIDED.md`](TASKS_GUIDED.md) walks
+you through it with the expected output.
+
+Commands are for macOS and Linux. On Windows type `.\demo`, `.\inspect` and `.\check`.
+
+**Rules:** work in `start/`. Never edit, delete or disable a test. Do not change anything in
+`demo/` or `checkpoint/`.
+
+**The data:** alice has a current account (id 1) with 500 and a savings account (id 2) with 500.
+Every demo run and every test starts from there.
+
+**The demo has two modes.** Without `--level` it runs the application's code, so it shows what your
+`@Transactional` settings do. With `--level` it runs the same anomaly as plain SQL at that level.
+
+---
+
+## Task 1: See the Statement That Does Not Add Up (15 min)
+
+**Story:** *A customer sends a screenshot of her statement: current 500, savings 500, total 1100.
+Nothing is in the error log. Before you change anything, reproduce it and find out what the database
+did.*
+
+**Steps:**
+1. `docker compose up -d`, then `./demo`. Do the lines add up to the total? Which isolation level
+ did the application's transaction run at? Nobody chose it: where does it come from?
+2. Open `StatementService.statement`. It is one transaction. Match the three queries to the
+ timeline. Between which two did session B commit?
+3. `./demo --anomaly phantom`. What is different about what session B does? What is wrong with the
+ statement this time?
+4. `./demo --anomaly non-repeatable-read --level read-committed` and
+ `./demo --anomaly phantom --level read-committed`. This is the same thing in plain SQL. In each
+ one, which statement does session A run twice, and what changes between the two runs?
+5. Maybe a lower level is even worse. `./demo --anomaly dirty-read --level read-uncommitted`. What
+ does session A read while B's change is uncommitted? What does `show transaction_isolation` say?
+
+**Acceptance Criteria** (`./check 1`, already passing: these tests document what Postgres does)
+- [ ] You can name the two anomalies and say what the difference between them is
+- [ ] You can say what the default isolation level is in Postgres, and what one query can and cannot
+ see at that level
+- [ ] You can explain why `@Transactional` alone did not protect the statement
+- [ ] You can say what READ UNCOMMITTED does in Postgres
+- [ ] The five tests in `ReadCommittedIT` pass
+
+**Hints:**
+- Non-repeatable read: a row you already read has **changed**. Phantom: a row you had not seen
+ **appeared** (or one you saw disappeared)
+- A transaction groups your writes. What it lets you see of other people's writes is a separate
+ setting
+
+---
+
+## Task 2: Fix the Statement With REPEATABLE READ (10 min)
+
+**Story:** *The statement must describe one moment in time. Whatever commits while it is being
+built must not show up in half of it. Fix `StatementService.statement`.*
+
+**Acceptance Criteria** (`./check 2`)
+- [ ] A deposit commits between the queries, and the lines still add up to the total
+ — `StatementIT.aDepositInTheMiddleDoesNotBreakTheStatement`
+- [ ] An account is opened between the queries, and the count still matches the lines
+ — `StatementIT.aNewAccountInTheMiddleDoesNotBreakTheStatement`
+- [ ] All of its queries run in one REPEATABLE READ transaction
+ — `StatementIT.statementRunsAtRepeatableRead`
+- [ ] The next statement shows the deposit — `StatementIT.theNextStatementSeesTheDeposit` (already
+ passing: keep it that way)
+- [ ] `./demo` and `./demo --anomaly phantom` print `RESULT: OK`
+- [ ] The baseline tests still pass (`./check`)
+
+**Hints:**
+- `@Transactional` has an `isolation` attribute
+- The method only reads. Keep `readOnly = true`
+- Could you also fix it without touching the isolation level? How many queries would you need?
+
+---
+
+## Task 3: Inspect the Snapshot (15 min)
+
+**Story:** *Your fix passes the tests. Now prove you know why.*
+
+**Steps:**
+1. You need two terminals. In the first: `./demo --level read-committed --pause`. While it waits,
+ in the second: `./inspect`. Find session A. Is `snapshot_xmin` filled in?
+2. The same with `./demo --level repeatable-read --pause`. What is in `snapshot_xmin` now? Look at
+ the `xmin` of account 1 under ACCOUNTS. Which transaction wrote the balance of 600, and can
+ session A see it?
+3. `./demo --pause` (the application this time), and `./inspect`. Which level does the `bank-app`
+ session report? Is it holding a snapshot?
+4. `./demo --anomaly dirty-read --level repeatable-read --pause`, and `./inspect`. Session A has run
+ `begin` but no query yet. Does it hold a snapshot? So when exactly is the snapshot taken?
+5. Session A in step 2 never saw the 600. When will it? Which test proves it?
+
+**Acceptance Criteria** (no tests: you answer)
+- [ ] You can say what a snapshot is, and when a REPEATABLE READ transaction takes it
+- [ ] You can say when a READ COMMITTED transaction takes a snapshot, and how long it keeps it
+- [ ] You can explain why nobody had to wait: not the deposit, not the statement
+- [ ] You can say whether REPEATABLE READ allows phantoms in Postgres, and what the SQL standard says
+- [ ] You can name one cost of a transaction that holds a snapshot for a long time
+
+---
+
+## Task 4: Stop the Lost Update, and Retry the Serialization Failure (25 min)
+
+**Story:** *Two withdrawals of 100 from the same account were paid out, and the balance went from
+500 to 400. A snapshot fixed the statement, so use it here too: `Withdrawer.withdraw` at REPEATABLE
+READ. Then deal with what the database does to the loser. Fix `Withdrawer`, then
+`WithdrawalService`.*
+
+**Acceptance Criteria** (`./check 4`)
+- [ ] One attempt that loses the race fails with Spring's `CannotAcquireLockException`, caused by
+ SQLSTATE `40001` — `LostUpdateIT.theLosingAttemptFailsWithCannotAcquireLockException`
+- [ ] Two withdrawals of 100 from the same account both go through, one on its second attempt, and
+ the balance is 300 — `LostUpdateIT.bothWithdrawalsGoThroughAndNothingIsLost`
+- [ ] When Postgres cancels the transaction, the withdrawal is tried again and succeeds
+ — `WithdrawalServiceRetryTest.retriesAfterASerializationFailure`
+- [ ] After 3 cancelled attempts it stops and throws `WithdrawalConflictException`
+ — `WithdrawalServiceRetryTest.givesUpAfterThreeAttempts`
+- [ ] Insufficient funds is not retried — `WithdrawalServiceRetryTest.doesNotRetryInsufficientFunds`
+ (already passing: keep it that way)
+- [ ] `WithdrawalService` is not `@Transactional`
+ — `WithdrawalServiceRetryTest.theRetryLoopIsOutsideTheTransaction` (already passing)
+- [ ] `./demo --anomaly lost-update` prints `RESULT: OK`
+
+**Hints:**
+- Change the isolation level first and run `./demo --anomaly lost-update` before writing the retry.
+ Read what session A gets
+- `CannotAcquireLockException` is a `ConcurrencyFailureException`. Catch that
+- The retry must run a **new transaction**. Why is the loop in `WithdrawalService` and not in
+ `Withdrawer`?
+
+---
+
+## Task 5: Inspect the Serialization Failure (15 min)
+
+**Story:** *Same again: the tests are green, now show what the database does.*
+
+**Steps:**
+1. `./demo --anomaly lost-update --level repeatable-read`. Which statement fails, in which session?
+ Write down the SQLSTATE and the message. Why did session B, which did exactly the same thing,
+ not fail?
+2. `./demo --anomaly lost-update --level read-committed`. Same steps, no error. What did the same
+ `update` do this time?
+3. Look at `Withdrawer.withdraw`. The exception does not come from the line that sets the balance.
+ Where does it come from, and what does that mean for a `try`/`catch` inside this method?
+4. `./demo --anomaly lost-update` (your fixed application). Which isolation level does attempt 2
+ report, and which balance does it start from? Where did that number come from?
+5. Suppose `Withdrawer.withdraw` also sent an email "you withdrew 100" before returning. What
+ happens to that email when the transaction is cancelled and run again?
+
+**Acceptance Criteria** (no tests: you answer)
+- [ ] You can quote the SQLSTATE and the message, and say which transaction gets it
+- [ ] You can name the exception Spring raises, and its parent that you catch
+- [ ] You can explain why the retry must be a new transaction that reads again
+- [ ] You can explain why the retry cannot live inside the `@Transactional` method
+- [ ] You can say what must not be inside a transaction that may be retried
+
+---
+
+## Task 6: Fix the Write Skew With SERIALIZABLE (15 min)
+
+**Story:** *Now the two withdrawals come from different accounts: 800 from current, 800 from
+savings, at the same time. Both pass the check "the accounts together hold at least 800". The
+accounts end at -600. Your REPEATABLE READ fix from Task 4 is in place and did nothing. Fix
+`Withdrawer.withdraw`.*
+
+**Acceptance Criteria** (`./check 6`)
+- [ ] 800 from current and 800 from savings at the same time: one goes through, the other is
+ refused, the accounts keep 200 — `WriteSkewIT.onlyOneOfTheTwoWithdrawalsGoesThrough`
+- [ ] Every attempt runs in a SERIALIZABLE transaction — `WriteSkewIT.everyAttemptRunsAtSerializable`
+- [ ] `./demo --anomaly write-skew` prints `RESULT: OK`
+- [ ] Task 4 is still green (`./check 4`)
+
+**Hints:**
+- Run `./demo --anomaly write-skew` first. Which rows does each session write? Is any row written
+ twice?
+- `./demo --anomaly write-skew --level repeatable-read`, then `--level serializable`
+- The retry from Task 4 is already there. Does it need to change?
+
+---
+
+## Task 7: Inspect SERIALIZABLE (15 min)
+
+**Story:** *SERIALIZABLE sounds like "one at a time". Find out what Postgres really does.*
+
+**Steps:**
+1. `./demo --anomaly write-skew --level serializable`. Which statement fails? Read the `Detail` and
+ the `Hint`. Did any session wait for the other one?
+2. `./demo --anomaly write-skew --level serializable --pause`, and `./inspect` in a second terminal.
+ Look at PREDICATE LOCKS. Who holds one, and what does it cover? Is `waits_for_pid` filled in for
+ anyone?
+3. `./demo --anomaly write-skew --pause` (the application), and `./inspect`. One predicate lock
+ belongs to a session that is not in the SESSIONS list. Whose is it, and why is it still there?
+4. In step 1 the transaction failed at `commit`. Read `WriteSkewIT.aFailedCommitIsAlsoCannotAcquireLockException`.
+ Does the retry need a second `catch` for that case?
+5. Read `WriteSkewIT.anInnerIsolationLevelIsIgnored`. A colleague calls `withdrawer.withdraw` from
+ a method that is already `@Transactional`. Which level does the withdrawal run at?
+6. The reporting team keeps its transactions at READ COMMITTED. Does your SERIALIZABLE withdrawal
+ protect the rule against a READ COMMITTED transaction that does the same read-check-write?
+
+**Acceptance Criteria** (no tests: you answer)
+- [ ] You can explain what SERIALIZABLE guarantees, in one sentence
+- [ ] You can explain how Postgres does it without making anyone wait
+- [ ] You can say at which moments a serializable transaction can be cancelled
+- [ ] You can name two costs of SERIALIZABLE
+- [ ] You can explain why the isolation level has to be set where the transaction starts
+
+---
+
+## Task 8: Compare Every Level, and Isolation Levels vs Locking (20 min)
+
+**Story:** *"Which isolation level would you use?" and "Why not just lock the row?" are the
+interview questions. Collect the evidence, then answer them.*
+
+**Steps:**
+1. `./demo --matrix`. Which two columns are identical? Which level is the first with no `HAPPENS`?
+ Compare the table with the one the SQL standard gives (it is in the guided task). Where is
+ Postgres stricter than the standard asks?
+2. `./demo --anomaly write-skew --for-update`. This is READ COMMITTED. What did session B do when
+ it tried to read? What did it read in the end?
+3. Put that next to `./demo --anomaly write-skew --level serializable`. In which run does somebody
+ wait? In which run is somebody cancelled?
+4. `./demo --anomaly write-skew --for-update --pause`, and `./inspect`. Find `waits_for_pid`. Look
+ at `xmax` of the two account rows.
+5. A new rule arrives: "a customer may have at most 3 accounts". Two sessions each count 2 accounts
+ and each insert one. Can `SELECT ... FOR UPDATE` on the existing rows stop that? Can
+ SERIALIZABLE?
+6. Decide, and say why: which would you use for the statement, for the withdrawal, and for
+ "decrement the stock of a product" from [`../07-locking`](../07-locking/)?
+
+**Acceptance Criteria** (`./check 8`, already passing, and you answer)
+- [ ] You can draw the table: four levels, which anomalies each one allows in Postgres
+- [ ] You can say in one sentence each what an isolation level is and what a lock is
+- [ ] You can say what the "loser" experiences with a lock, and with a higher isolation level
+- [ ] You can give one situation where `SELECT ... FOR UPDATE` is the better tool, and one where
+ only SERIALIZABLE works
+- [ ] `IsolationVsLockingIT` passes
+
+---
+
+## Questions to Ask Afterwards
+
+Answer out loud, in full sentences, before reading the answer in brackets.
+
+- What are the four isolation levels? (READ UNCOMMITTED, READ COMMITTED, REPEATABLE READ,
+ SERIALIZABLE, weakest first. Each one rules out more of what a transaction can observe of other
+ transactions that run at the same time.)
+- What is the default in Postgres? (READ COMMITTED. Every statement sees what was committed when
+ that statement started. Two statements in the same transaction can see different data. Spring's
+ `@Transactional` without an `isolation` attribute uses the database default.)
+- Dirty read, non-repeatable read, phantom read: what is each? (Dirty: you read a change that was
+ never committed. Non-repeatable: you read a row twice and it changed in between, because someone
+ committed. Phantom: you run a query twice and a row appeared or disappeared, because someone
+ committed an insert or delete.)
+- Does READ UNCOMMITTED give you dirty reads in Postgres? (No. Postgres accepts the level and runs
+ it as READ COMMITTED. There is no way to read uncommitted data in Postgres.)
+- What does REPEATABLE READ do in Postgres? (The transaction takes one snapshot at its first query
+ and reads from it until it ends. So no non-repeatable reads and, in Postgres, no phantoms either,
+ although the SQL standard would allow them. If it tries to update a row that someone changed after
+ the snapshot, it is cancelled with SQLSTATE 40001.)
+- What is write skew? (Two transactions read the same data, each makes a decision from it, and each
+ writes a different row. No row is written twice, so nothing looks like a conflict, but the two
+ decisions together break a rule. REPEATABLE READ allows it. SERIALIZABLE does not.)
+- What does SERIALIZABLE guarantee? (The result is the same as if the transactions had run one
+ after another, in some order. Postgres does not run them one at a time and does not make them
+ wait. It tracks what each one read, and when the overlap cannot be explained by any order, it
+ cancels one with 40001.)
+- What do you do with a 40001? (Run the whole transaction again, a limited number of times. It is
+ not a bug in the request. In Spring it arrives as `CannotAcquireLockException`; catch its parent
+ `ConcurrencyFailureException`. In production add a short random delay between attempts.)
+- Where does the retry go? (Outside the transaction, in a different bean. A cancelled transaction
+ cannot be continued, so every attempt needs a new one, and a call to a method on `this` does not
+ go through the transactional proxy. With Hibernate the UPDATE is sent at commit, so the exception
+ comes out of the call to the transactional method, not from a line inside it.)
+- What must not be in a transaction that can be retried? (Anything the database cannot roll back:
+ an email, an HTTP call, a message. It would happen once per attempt. Do it after the commit.)
+- Is an isolation level a lock? (No. An isolation level is a setting of one transaction: what it may
+ see. A lock is a claim on specific rows that makes other transactions wait. With a lock the loser
+ waits and then carries on with fresh data. A higher isolation level in Postgres adds no waiting:
+ the loser is cancelled and must retry.)
+- When `SELECT ... FOR UPDATE` and when SERIALIZABLE? (Lock when you know exactly which rows you
+ are going to change and conflicts are common: a stock counter, a seat. Use SERIALIZABLE when the
+ decision depends on a set of rows, or on rows that do not exist yet, which you cannot lock. Often
+ the best answer is neither: one conditional UPDATE, or a constraint.)
+- You put `@Transactional(isolation = SERIALIZABLE)` on a method and it still runs at READ
+ COMMITTED. Why? (It was called from inside a transaction that was already open. The method joined
+ it, and a transaction has one level, fixed when it starts. Spring ignores the inner setting
+ without telling you.)
+- Is SERIALIZABLE on one method enough? (No. Postgres only guarantees it between transactions that
+ are all SERIALIZABLE. A READ COMMITTED transaction that does the same read-check-write can still
+ cause write skew against it.)
+- What does a long REPEATABLE READ transaction cost? (It pins a snapshot. While it is open, VACUUM
+ cannot remove any row version that the snapshot might still need, so tables bloat. Keep them
+ short.)
+- Do other databases behave the same? (No. The level names come from the SQL standard, the
+ behaviour does not. MySQL's InnoDB, for example, defaults to REPEATABLE READ, not READ COMMITTED.
+ Always say which database you are talking about.)
+
+## Tips for Interviewers
+
+- The most common wrong answer is a recited table: "READ UNCOMMITTED allows dirty reads, ..." Ask
+ "in Postgres?". A candidate who has run it knows that the first two levels are the same level.
+- Ask the candidate to predict `./demo --anomaly write-skew --level repeatable-read` before running
+ it. Most people who say "REPEATABLE READ gives me a consistent view" expect it to be safe.
+- "I would set it to SERIALIZABLE" is half an answer. The other half is the retry. Ask what the
+ user sees when the transaction is cancelled, and watch where the candidate puts the loop.
+- A retry loop inside the `@Transactional` method never runs: the exception appears at commit, after
+ the method has returned. It is the bug that separates levels.
+- Listen for "isolation level" and "lock" being used as the same word. Task 8 steps 2 and 3 are the
+ quickest way to pull them apart: same scenario, one run waits, the other is cancelled.
+- For senior candidates, ask Task 8 step 5, then ask for a third option. A good answer is a unique
+ constraint or a counter row that every writer has to lock.
diff --git a/java/concepts/junior-mid/09-isolation-levels/README.md b/java/concepts/junior-mid/09-isolation-levels/README.md
new file mode 100644
index 0000000..a0aa555
--- /dev/null
+++ b/java/concepts/junior-mid/09-isolation-levels/README.md
@@ -0,0 +1,180 @@
+# Isolation Levels — What One Transaction Sees of Another
+
+> **In `start/`, `./check` FAILS on purpose: 22 of 31 checks pass.** That is the exercise, not a
+> broken checkout. Tasks 2, 4 and 6 turn the other 9 green.
+
+A bank prints a statement: current account 500, savings 500, **total 1100**. Nothing crashed. A
+deposit was committed between the query that read the lines and the query that read the total. This
+project lets you watch that happen, step by step, in two database sessions. Then you raise the
+isolation level, meet the error that comes with it (SQLSTATE `40001`), and handle it.
+
+It answers the interview questions students most often get wrong:
+
+- "What are the four isolation levels, and which anomalies does each one allow?"
+- "What is the default in Postgres? Does READ UNCOMMITTED give you dirty reads there?"
+- "What is the difference between a non-repeatable read and a phantom read?"
+- "What is write skew, and why does REPEATABLE READ not stop it?"
+- "What happens when a SERIALIZABLE transaction fails? Where does the retry go?"
+- "Isolation level or `SELECT ... FOR UPDATE`: what is the difference?"
+
+## Tech Stack
+
+- **Java 25**, **Spring Boot 4**, Spring Data JPA (Hibernate 7)
+- **PostgreSQL 17** in Docker
+- JUnit 5, AssertJ, Testcontainers
+
+## What you need
+
+- JDK 25
+- Docker, running
+
+## Getting Started
+
+Work in `start/`. Commands are shown for macOS and Linux; on Windows type `.\demo` where you see
+`./demo` (same for `inspect` and `check`).
+
+```bash
+cd start
+docker compose up -d # Postgres on port 5448
+./demo # watch a statement that does not add up
+./check # 22 of 31 pass: that is your starting point
+```
+
+The first run downloads Maven and the dependencies, so it takes a minute or two.
+
+When you are finished: `docker compose down`.
+
+## The three tools
+
+### `./demo` — see what happens
+
+Two sessions, A and B, run their steps in a fixed order, so the anomaly happens on every run. The
+demo prints each step and ends with a `RESULT:` line. Every run starts from the same data: alice
+has a current account (id 1) with 500 and a savings account (id 2) with 500.
+
+It has two modes:
+
+- **Without `--level` it runs the application's code** (`StatementService`, `WithdrawalService`).
+ What you see depends on the `@Transactional` settings in the code, so this is how you see your
+ fix work.
+- **With `--level` it runs the same anomaly as plain SQL** at the level you choose. This is what
+ Postgres itself does, whatever the Java code says.
+
+```
+./demo the application's statement while a deposit commits
+./demo --anomaly phantom dirty-read | non-repeatable-read | phantom | lost-update | write-skew
+./demo --anomaly write-skew --level serializable read-uncommitted | read-committed | repeatable-read | serializable
+./demo --anomaly write-skew --for-update plain SQL with SELECT ... FOR UPDATE instead of a higher level
+./demo --matrix every anomaly at every level, as one table
+./demo --pause hold the transactions open for 15 seconds, for ./inspect
+./demo --help
+```
+
+### `./inspect` — look inside the database
+
+Shows the account rows with the transaction that wrote each one (`xmin`), every session that is
+inside a transaction, its isolation level, whether it is holding a snapshot, which session it is
+waiting for, and the predicate locks of SERIALIZABLE sessions. Run it in a second terminal while
+`./demo --pause` is running. `./inspect --watch` refreshes every second.
+
+### `./check` — are the acceptance criteria met?
+
+`./check 2` runs the tests for Task 2 and prints one line per criterion. `./check` runs everything.
+`./mvnw verify` runs the same tests the usual Maven way.
+
+The tests are the acceptance criteria. **Never edit, delete or disable a test.**
+
+## The code
+
+```
+start/src/main/java/com/amigoscode/isolation/
+├── statement/
+│ ├── StatementService.java three queries in one transaction. BUG 1 IS HERE
+│ └── Statement.java the lines, the account count and the total
+├── withdrawal/
+│ ├── WithdrawalService.java calls Withdrawer; the retry goes here
+│ └── Withdrawer.java one transaction: read, check, write. BUGS 2 AND 3 ARE HERE
+├── account/ the entity and the queries
+├── checkpoint/ a named point between a read and a write, where the demo and
+│ the tests let the other session in. Nothing to change here
+└── demo/ the demo and inspect tools. Nothing to change here
+```
+
+The bank's rule for withdrawals: **one account may go below zero, as long as all of the customer's
+accounts together stay at zero or above.**
+
+## Two ways to work
+
+- **[`INTERVIEW_TASKS.md`](INTERVIEW_TASKS.md)**: challenge mode. A story, acceptance criteria and
+ hints for each task. Use this if you want to work it out yourself.
+- **[`TASKS_GUIDED.md`](TASKS_GUIDED.md)**: the same eight tasks, step by step, with the output you
+ should see and an explanation of why. Use this to learn the concept, or when you are stuck.
+
+Both files use the same task numbers.
+
+| Task | What you do | Checked by |
+|---|---|---|
+| 1 | See the statement that does not add up | `./check 1` (passes: it documents what Postgres does) |
+| 2 | Fix the statement with REPEATABLE READ | `./check 2` |
+| 3 | Inspect the snapshot | you answer questions |
+| 4 | Stop the lost update, and retry the serialization failure | `./check 4` |
+| 5 | Inspect the serialization failure | you answer questions |
+| 6 | Fix the write skew with SERIALIZABLE | `./check 6` |
+| 7 | Inspect SERIALIZABLE | you answer questions |
+| 8 | Compare every level, and isolation levels vs locking | `./check 8` (passes) and you answer questions |
+
+## Isolation levels are not locks
+
+Students mix these up in interviews, so keep them apart from the start.
+
+| | Isolation level | Lock (`SELECT ... FOR UPDATE`) |
+|---|---|---|
+| What it is | A setting of the **transaction**: what it may see of other transactions | A claim on **specific rows**: nobody else may change or lock them until I finish |
+| Who is affected | Only the transaction that sets it | Every other transaction that wants those rows |
+| What the other one experiences | No extra waiting. In Postgres a conflict **cancels** one transaction with SQLSTATE `40001` | It **waits** until the lock is released |
+| What the application must do | Retry the cancelled transaction | Keep the transaction short, lock in a consistent order |
+| Reach for it when | The decision depends on many rows, or on rows that do not exist yet. Conflicts are rare | You know exactly which rows you will change, and redoing the work is expensive or conflicts are common |
+
+Locking, optimistic and pessimistic, has its own project: [`../07-locking`](../07-locking/).
+
+## Solution
+
+`solution/` is the same project with every task done: `cd solution && ./check` prints 31 of 31.
+
+To start again from scratch: `git checkout -- start` (this throws away your changes in `start/`).
+
+
+Spoiler: the three bugs and the fixes
+
+**Bug 1, the statement (Task 2).** `StatementService.statement` runs three queries in a READ
+COMMITTED transaction (the Postgres default). Each query sees whatever is committed when that query
+starts. A deposit between them is a **non-repeatable read**, a new account is a **phantom read**.
+Fix: `@Transactional(readOnly = true, isolation = Isolation.REPEATABLE_READ)`. The transaction takes
+one snapshot at its first query and every later query reads from it.
+
+**Bug 2, the lost update (Task 4).** `Withdrawer.withdraw` reads the balance, subtracts in Java and
+writes the result. Two withdrawals from the same account both read 500 and both write 400. At
+REPEATABLE READ Postgres cancels the second writer: SQLSTATE `40001`, "could not serialize access
+due to concurrent update". Spring raises `CannotAcquireLockException`. `WithdrawalService` catches
+it (as `ConcurrencyFailureException`) and runs the withdrawal again in a **new transaction**, up to
+3 attempts, then throws `WithdrawalConflictException`.
+
+**Bug 3, the write skew (Task 6).** Two withdrawals from **different** accounts each check the
+combined balance, each see 1000, each write their own row. No row is written twice, so REPEATABLE
+READ has nothing to object to, and the accounts end at -600. Fix:
+`@Transactional(isolation = Isolation.SERIALIZABLE)`. Postgres tracks what each transaction read,
+and cancels one of them with `40001`. The retry from Task 4 handles it.
+
+**What each level stops in Postgres** (`./demo --matrix`):
+
+| | read uncommitted | read committed | repeatable read | serializable |
+|---|---|---|---|---|
+| dirty read | no | no | no | no |
+| non-repeatable read | HAPPENS | HAPPENS | no | no |
+| phantom read | HAPPENS | HAPPENS | no | no |
+| lost update | HAPPENS | HAPPENS | 40001 | 40001 |
+| write skew | HAPPENS | HAPPENS | HAPPENS | 40001 |
+
+READ UNCOMMITTED is accepted and runs as READ COMMITTED: Postgres has no dirty reads.
+
+
diff --git a/java/concepts/junior-mid/09-isolation-levels/TASKS_GUIDED.md b/java/concepts/junior-mid/09-isolation-levels/TASKS_GUIDED.md
new file mode 100644
index 0000000..1e151aa
--- /dev/null
+++ b/java/concepts/junior-mid/09-isolation-levels/TASKS_GUIDED.md
@@ -0,0 +1,890 @@
+# Guided Tasks — Isolation Levels
+
+The same eight tasks as [`INTERVIEW_TASKS.md`](INTERVIEW_TASKS.md), step by step: the command to
+run, the output you should see, why it happens, and the change to make.
+
+Commands are for macOS and Linux. On Windows type `.\demo`, `.\inspect` and `.\check`.
+
+Process ids (`pid`), transaction ids (`xmin`, `own_xid`) and times will differ on your machine. The
+steps, the values and the `RESULT` line should match: the demo does not race two threads, it runs
+the steps of two sessions in a fixed order.
+
+**Before you start**
+
+```bash
+cd start
+docker compose up -d
+```
+
+**How to read the demo.** Session A is on the left, session B is indented. `->` is what came back.
+`#` is something the application works out in Java, outside the database.
+
+**Two modes.** `./demo` without `--level` runs the application's code, so it changes when you change
+the code. `./demo --level ...` runs the same anomaly as plain SQL at the level you ask for, whatever
+the code says.
+
+---
+
+## Task 1: See the Statement That Does Not Add Up
+
+No code in this task. You are collecting evidence.
+
+### Run it
+
+```bash
+./demo
+```
+
+### What you should see
+
+```
+Anomaly: non-repeatable-read | running the application: StatementService.statement
+Session A is the application, building alice's statement: the lines first, then the count and the total.
+Session B deposits 100 and commits in between.
+Before: alice has two accounts, current (id 1) = 500 and savings (id 2) = 500.
+
+ A | StatementService.statement("alice")
+ A | -> transaction isolation level: read committed
+ A | -> query 1 done: the lines are read
+ B | begin
+ B | update account set balance = balance + 100 where id = 1
+ B | -> 1 row
+ B | commit
+ A | -> queries 2 and 3 done: the count and the total are read
+
+The statement the customer gets:
+ current 500
+ savings 500
+ -------------------
+ 2 accounts 1100
+
+RESULT: NON-REPEATABLE READ. The lines add up to 1000, the total says 1100. The queries of one transaction saw two different moments.
+```
+
+500 + 500 = 1100. Nothing crashed and nothing was logged. Every number on that statement was true
+at some moment. They were just not true at the same moment.
+
+### Find it in the code
+
+Open `StatementService.statement`:
+
+```java
+@Transactional(readOnly = true)
+public Statement statement(String owner) {
+ List lines = accounts.findByOwnerOrderById(owner)...; // QUERY 1: the lines
+ checkpoint.reached(Checkpoint.LINES_READ); // ...time passes...
+ long accountCount = accounts.countByOwner(owner); // QUERY 2: how many accounts
+ long total = accounts.totalBalance(owner); // QUERY 3: the total
+ return new Statement(owner, lines, accountCount, total);
+}
+```
+
+It is `@Transactional`, and it still went wrong. A transaction makes **your writes** succeed or fail
+together. What you can **see** of other people's writes is a different setting: the **isolation
+level**. Nobody set one here, so the transaction ran at the database default. The demo printed it:
+`read committed`.
+
+At READ COMMITTED every **statement** sees what was committed at the moment that statement started.
+Query 1 started before the deposit, queries 2 and 3 after it.
+
+(`checkpoint.reached(...)` does nothing in production. The demo and the tests use it to let session
+B in at exactly that point. Without it you would have to be unlucky to see the bug, which is what
+makes it so hard to find in real life.)
+
+### The same thing in plain SQL
+
+```bash
+./demo --anomaly non-repeatable-read --level read-committed
+```
+
+```
+ A | begin isolation level read committed
+ A | select balance from account where id = 1
+ A | -> 500
+ B | begin
+ B | update account set balance = balance + 100 where id = 1
+ B | -> 1 row
+ B | commit
+ A | select balance from account where id = 1
+ A | -> 600
+ A | commit
+
+RESULT: NON-REPEATABLE READ. Session A read the same row twice in one transaction and got 500, then 600.
+```
+
+Same transaction, same query, same row, two answers. That is a **non-repeatable read**.
+
+### A row that was not there
+
+```bash
+./demo --anomaly phantom
+```
+
+```
+ B | insert into account (id, owner, name, balance) values (3, 'alice', 'holiday', 250)
+ ...
+The statement the customer gets:
+ current 500
+ savings 500
+ -------------------
+ 3 accounts 1250
+
+RESULT: PHANTOM READ. The statement lists 2 accounts and then says there are 3. The lines add up to 1000, the total says 1250.
+```
+
+This time no row that A had read was changed. A **new row** appeared that matches A's query. That is
+a **phantom read**. In plain SQL: `./demo --anomaly phantom --level read-committed` counts 2 rows,
+then 3.
+
+| | What happened to the data A reads |
+|---|---|
+| Non-repeatable read | A row A already read was **updated** (or deleted) and committed |
+| Phantom read | A row A had never seen was **inserted** and committed, and now matches A's query |
+
+### Is the level below even worse?
+
+The textbook says READ UNCOMMITTED allows **dirty reads**: reading a change that was never
+committed. Try it:
+
+```bash
+./demo --anomaly dirty-read --level read-uncommitted
+```
+
+```
+ A | begin isolation level read uncommitted
+ A | show transaction_isolation
+ A | -> read uncommitted
+ B | begin
+ B | update account set balance = 0 where id = 1
+ B | -> 1 row
+ A | select balance from account where id = 1
+ A | -> 500
+ B | rollback
+ A | commit
+
+RESULT: NO DIRTY READ. Session A read 500 while B's uncommitted 0 was in the table. Postgres accepts READ UNCOMMITTED and runs it as READ COMMITTED.
+```
+
+Postgres takes the level, even reports it back, and then behaves as READ COMMITTED. **There are no
+dirty reads in Postgres, at any level.** If an interviewer asks "which level allows dirty reads?",
+the textbook answer is READ UNCOMMITTED, and the good answer adds "but not in Postgres".
+
+### Check
+
+```bash
+./check 1
+```
+
+```
+ [PASS] READ COMMITTED: non-repeatable read. One transaction reads a balance twice and gets 500, then 600
+ ...
+ 5 of 5 pass
+```
+
+These pass on purpose. They pin down what Postgres does, so you can see what the fixes change.
+
+---
+
+## Task 2: Fix the Statement With REPEATABLE READ
+
+**The idea:** the three queries must all look at the database as it was at one moment. That is what
+REPEATABLE READ gives you: the transaction takes one **snapshot** and every query reads from it.
+
+Before you start, `./check 2` says 3 of 6 pass. The three that pass describe Postgres. The three
+that fail describe your code.
+
+### The change
+
+In `StatementService`:
+
+```java
+@Transactional(readOnly = true, isolation = Isolation.REPEATABLE_READ)
+public Statement statement(String owner) {
+```
+
+Import `org.springframework.transaction.annotation.Isolation`. That is the whole fix.
+
+### After
+
+```bash
+./demo
+```
+
+```
+ A | StatementService.statement("alice")
+ A | -> transaction isolation level: repeatable read
+ ...
+The statement the customer gets:
+ current 500
+ savings 500
+ -------------------
+ 2 accounts 1000
+
+RESULT: OK. 2 lines, 2 accounts, and the lines add up to the total: 1000. What session B committed is not in this statement. It will be in the next one.
+```
+
+Three things to notice:
+
+- **B was not blocked.** Its deposit went through and is committed. A just does not look at it.
+- **The statement is not "wrong" for showing 500.** It is a correct picture of the moment the
+ transaction took its snapshot. The next statement shows 600.
+- `./demo --anomaly phantom` is also `OK` now. The SQL standard lets REPEATABLE READ have phantoms.
+ **Postgres does not have them**: a snapshot does not contain rows that were inserted later.
+
+`./check 2` now says 6 of 6 pass.
+
+### You did not have to use an isolation level
+
+One statement always sees one moment, even at READ COMMITTED. If you read the lines once and add
+them up in Java, or fetch everything in one query, there is no second query to disagree with the
+first. That is often the simplest fix. You need REPEATABLE READ when one piece of work really needs
+several queries that must agree, like a report or an export.
+
+---
+
+## Task 3: Inspect the Snapshot
+
+You need two terminals, both in `start/`.
+
+### Step 1: READ COMMITTED holds nothing between statements
+
+Terminal 1: `./demo --level read-committed --pause`. Terminal 2, while it says "Paused for 15
+seconds": `./inspect`.
+
+```
+SESSIONS INSIDE A TRANSACTION (snapshot_xmin is filled in while the session holds a snapshot)
+ pid session state snapshot_xmin own_xid waits_for_pid in_transaction_ms last_statement
+ ---- ----------------------- ------------------- ------------- ------- ------------- ----------------- ----------------------------------------
+ 2844 demo A (read committed) idle in transaction 8958 select balance from account where id = 1
+```
+
+Session A is in the middle of a transaction and has already run a SELECT. `snapshot_xmin` is empty:
+it is holding **no snapshot**. At READ COMMITTED a snapshot lives for one statement. The next
+statement takes a new one, and sees whatever is committed by then.
+
+(Postgres has no column that shows another session's isolation level. The demo's sessions put their
+own level into their name, which is why you can read it here.)
+
+### Step 2: REPEATABLE READ keeps one
+
+`./demo --level repeatable-read --pause` in terminal 1, `./inspect` in terminal 2:
+
+```
+ACCOUNTS (what a NEW transaction would read. xmin = the transaction that wrote this version of
+ the row, xmax = a transaction that has locked or replaced it, 0 = none)
+ id name balance xmin xmax
+ -- ------- ------- ---- ----
+ 1 current 600 965 0
+ 2 savings 500 964 0
+
+SESSIONS INSIDE A TRANSACTION (snapshot_xmin is filled in while the session holds a snapshot)
+ pid session state snapshot_xmin own_xid waits_for_pid in_transaction_ms last_statement
+ ---- ------------------------ ------------------- ------------- ------- ------------- ----------------- ----------------------------------------
+ 5071 demo A (repeatable read) idle in transaction 965 8324 select balance from account where id = 1
+```
+
+Your numbers will differ. Read them like this:
+
+- Every transaction that writes gets a number, a **transaction id**. Every row version remembers the
+ transaction that wrote it: that is `xmin` in ACCOUNTS. The balance of 600 was written by
+ transaction 965, session B's deposit.
+- Session A's `snapshot_xmin` is 965. It means: "my snapshot contains what transactions **before**
+ 965 committed". Transaction 965 itself is not in it.
+- So when A reads account 1 again, Postgres skips the version written by 965 and gives A the older
+ version, the one with 500. Postgres keeps old versions of rows for exactly this purpose. The
+ technique is called MVCC, multi-version concurrency control.
+
+That is also why nobody waited. B wrote a **new version** of the row, A keeps reading the **old
+version**. Readers do not block writers and writers do not block readers.
+
+### Step 3: your application
+
+`./demo --pause` in terminal 1, `./inspect` in terminal 2:
+
+```
+ 2976 bank-app (repeatable read) idle in transaction 915 ...
+```
+
+The application's session reports `repeatable read` and holds a snapshot. That is your annotation
+at work.
+
+### Step 4: when is the snapshot taken?
+
+`./demo --anomaly dirty-read --level repeatable-read --pause`, then `./inspect`:
+
+```
+ 3915 demo A (repeatable read) idle in transaction 13957 show transaction_isolation
+```
+
+A has run `begin isolation level repeatable read`, and `snapshot_xmin` is still empty. **The
+snapshot is taken by the first query, not by `begin`.**
+
+### Step 5: when does A see the 600?
+
+In its next transaction. The snapshot ends with the transaction. `StatementIT.theNextStatementSeesTheDeposit`
+proves it for the application.
+
+### What to take away
+
+- READ COMMITTED: a new snapshot for every statement.
+- REPEATABLE READ: one snapshot, taken at the first query, kept until the transaction ends.
+- Nobody waits. The price is paid somewhere else: while a snapshot is open, Postgres cannot clean
+ up row versions that the snapshot might still need. A transaction that stays open for an hour
+ makes every busy table grow. Keep them short.
+
+---
+
+## Task 4: Stop the Lost Update, and Retry the Serialization Failure
+
+### Before
+
+```bash
+./demo --anomaly lost-update
+```
+
+```
+ A | WithdrawalService.withdraw(1, 100)
+ A | -> attempt 1, transaction isolation level: read committed
+ A | -> funds checked: enough for 100
+ B | WithdrawalService.withdraw(1, 100)
+ ...
+ B | -> returns 400, the new balance of account 1
+ A | -> returns 400, the new balance of account 1
+
+RESULT: LOST UPDATE. 2 withdrawals of 100 were paid out, but the balance only went from 500 to 400.
+```
+
+Open `Withdrawer.withdraw`. It reads the balance, subtracts **in Java**, and writes the result:
+
+```java
+Account account = accounts.findById(accountId)...; // READ this account
+long available = accounts.totalBalance(account.getOwner()); // READ all the customer's accounts
+if (available < amount) { throw new InsufficientFundsException(...); } // CHECK the rule
+checkpoint.reached(Checkpoint.FUNDS_CHECKED); // ...time passes...
+account.setBalance(account.getBalance() - amount); // WRITE a value computed from the READ
+```
+
+Both sessions read 500, both wrote 500 - 100 = 400. The bank paid out 200 and took 100 off the
+account. (This is the bug of [`../07-locking`](../07-locking/). There you fixed it with locks. Here
+you fix it with an isolation level, and see what is different.)
+
+### Step 1: REPEATABLE READ
+
+In `Withdrawer`:
+
+```java
+@Transactional(isolation = Isolation.REPEATABLE_READ)
+public long withdraw(long accountId, long amount) {
+```
+
+Import `org.springframework.transaction.annotation.Isolation`.
+
+### Look before you go on
+
+Do not write the retry yet. Run:
+
+```bash
+./demo --anomaly lost-update
+```
+
+```
+ A | WithdrawalService.withdraw(1, 100)
+ A | -> attempt 1, transaction isolation level: repeatable read
+ A | -> funds checked: enough for 100
+ B | WithdrawalService.withdraw(1, 100)
+ ...
+ B | -> returns 400, the new balance of account 1
+ A | -> THROWS org.springframework.dao.CannotAcquireLockException
+ A | -> caused by PSQLException, SQLSTATE 40001: ERROR: could not serialize access due to concurrent update
+
+Withdrawals paid out: 1 x 100
+Current (id 1): 400
+
+RESULT: NOT HANDLED. The data is right, because Postgres cancelled session A's transaction. But the customer got a CannotAcquireLockException. Nothing was wrong with the request: it has to be run again.
+```
+
+The data is already correct: one withdrawal paid out, balance 400. Session A wanted to update a row
+that had changed since A took its snapshot. At READ COMMITTED Postgres lets that through. At
+REPEATABLE READ it refuses: A's decision was made from a picture that is no longer true.
+
+This error has a name and a number: a **serialization failure**, SQLSTATE **`40001`**. It does not
+mean the request was wrong. It means "this transaction cannot finish, run it again".
+
+Note the Java exception. Spring Boot 4 with Hibernate 7 turns `40001` into
+`CannotAcquireLockException`. The name is misleading: no lock was involved and nobody waited. Its
+parent classes are `PessimisticLockingFailureException`, then `ConcurrencyFailureException`.
+
+Half a fix: the data is safe and the customer sees a crash.
+
+### Step 2: retry in WithdrawalService
+
+Replace the `withdraw` method in `WithdrawalService`:
+
+```java
+public long withdraw(long accountId, long amount) {
+ for (int attempt = 1; ; attempt++) {
+ try {
+ return withdrawer.withdraw(accountId, amount);
+ } catch (ConcurrencyFailureException e) {
+ if (attempt == MAX_ATTEMPTS) {
+ throw new WithdrawalConflictException(accountId, attempt, e);
+ }
+ }
+ }
+}
+```
+
+Import `org.springframework.dao.ConcurrencyFailureException`.
+
+Three things to notice:
+
+- **The retry is in `WithdrawalService`, not in `Withdrawer`.** `withdrawer.withdraw(...)` is a call
+ to another Spring bean, so every attempt goes through the transactional proxy and gets a brand
+ new transaction, with a new snapshot. A cancelled transaction cannot be continued. If the loop
+ were inside the `@Transactional` method, it would not even see the exception (Task 5 shows why).
+- **Only the serialization failure is retried.** `InsufficientFundsException` is not caught: trying
+ again cannot put money in the account.
+- **It gives up.** After 3 attempts it throws `WithdrawalConflictException`. A retry loop with no
+ limit can spin for ever under load.
+
+### After
+
+```bash
+./demo --anomaly lost-update
+```
+
+```
+ B | -> returns 400, the new balance of account 1
+ A | -> attempt 2 (a new transaction: the last one did not commit), transaction isolation level: repeatable read
+ A | -> funds checked: enough for 100
+ A | -> returns 300, the new balance of account 1
+
+Withdrawals paid out: 2 x 100
+Current (id 1): 300
+
+RESULT: OK. 2 x 100 paid out, both accounts together went from 1000 to 800. Session A was cancelled once and ran again in a new transaction.
+```
+
+`./check 4` now says 8 of 8 pass. Run `./check` too: Task 2 must still be green.
+
+---
+
+## Task 5: Inspect the Serialization Failure
+
+### Step 1: which statement fails
+
+```bash
+./demo --anomaly lost-update --level repeatable-read
+```
+
+```
+ A | begin isolation level repeatable read
+ A | select balance from account where id = 1
+ A | -> 500
+ B | begin isolation level repeatable read
+ B | select balance from account where id = 1
+ B | -> 500
+ B | # 500 - 100 = 400, worked out in the application
+ B | update account set balance = 400 where id = 1
+ B | -> 1 row
+ B | commit
+ A | # 500 - 100 = 400, worked out in the application
+ A | update account set balance = 400 where id = 1
+ A | -> ERROR, SQLSTATE 40001: could not serialize access due to concurrent update
+ A | rollback
+ A | # this transaction was cancelled, so there is nothing to commit
+```
+
+A and B did exactly the same thing. B committed first, so B won. The rule is **first committer
+wins**: the transaction that tries to change a row which someone else changed after its snapshot is
+the one that is cancelled.
+
+### Step 2: the same steps at READ COMMITTED
+
+```bash
+./demo --anomaly lost-update --level read-committed
+```
+
+No error. A's `update account set balance = 400` simply runs, on top of B's 400. READ COMMITTED has
+no snapshot to compare with, so it cannot know that A's 400 was computed from an old 500.
+
+### Step 3: where the exception comes from
+
+In `Withdrawer.withdraw`, `account.setBalance(...)` only changes a Java object. Hibernate sends the
+UPDATE when the transaction **commits**, which is after the method has returned. So the exception
+does not come from any line inside `withdraw`. It comes out of the **call** to
+`withdrawer.withdraw(...)`.
+
+A `try`/`catch` inside the `@Transactional` method would never see it. This is the second reason
+the retry has to be outside.
+
+### Step 4: the retry reads again
+
+In the `After` output of Task 4, attempt 2 "returns 300". It did not reuse the 500 from attempt 1.
+It is a new transaction with a new snapshot, it read 400, and it wrote 400 - 100 = 300. A retry
+that reuses values from the failed attempt brings the lost update straight back.
+
+### Step 5: what must not be inside
+
+Everything in a cancelled transaction is rolled back by the database. An email, an HTTP call or a
+message to a queue is not. If `withdraw` sent an email, the customer would get one per attempt, for
+one withdrawal. Whatever cannot be rolled back goes after the commit, outside the method that is
+retried.
+
+### What to take away
+
+- SQLSTATE `40001` = serialization failure = "run this transaction again".
+- Spring: `CannotAcquireLockException`. Catch `ConcurrencyFailureException`.
+- The retry is a new transaction that reads everything again, in another bean, with a limit.
+- Nobody waited at any point. The loser paid by doing its work twice.
+
+---
+
+## Task 6: Fix the Write Skew With SERIALIZABLE
+
+### Before
+
+Your code is at REPEATABLE READ with a retry. Now the two withdrawals use **different** accounts:
+
+```bash
+./demo --anomaly write-skew
+```
+
+```
+ A | WithdrawalService.withdraw(1, 800)
+ A | -> attempt 1, transaction isolation level: repeatable read
+ A | -> funds checked: enough for 800
+ B | WithdrawalService.withdraw(2, 800)
+ ...
+ B | -> returns -300, the new balance of account 2
+ A | -> returns -300, the new balance of account 1
+
+Withdrawals paid out: 2 x 800
+Current (id 1): -300
+Savings (id 2): -300
+Both together: -600
+
+RESULT: WRITE SKEW. Both withdrawals of 800 went through and the accounts hold -600 together. The rule is broken, and neither transaction changed a row the other one changed.
+```
+
+The rule says the accounts together must stay at 0 or above. They hold -600, and REPEATABLE READ
+did not object.
+
+### Why REPEATABLE READ cannot see it
+
+```bash
+./demo --anomaly write-skew --level repeatable-read
+```
+
+```
+ A | begin isolation level repeatable read
+ A | select balance from account where owner = 'alice' order by id
+ A | -> 500, 500
+ A | # 500 + 500 = 1000, enough for 800: go ahead
+ B | begin isolation level repeatable read
+ B | select balance from account where owner = 'alice' order by id
+ B | -> 500, 500
+ B | # 500 + 500 = 1000, enough for 800: go ahead
+ A | update account set balance = balance - 800 where id = 1
+ A | -> 1 row
+ B | update account set balance = balance - 800 where id = 2
+ B | -> 1 row
+ A | commit
+ B | commit
+
+RESULT: WRITE SKEW. Both sessions saw 1000, both withdrew 800, both committed. ...
+```
+
+In Task 4 both sessions wrote **the same row**, and that is what REPEATABLE READ checks. Here A
+writes row 1 and B writes row 2. No row is written twice. Each decision was right for the snapshot
+it was made from. Together they are wrong.
+
+This is **write skew**: two transactions read overlapping data, decide, and write **different**
+rows. The classic example is a hospital rule "at least one doctor must be on call": two doctors
+each see two on call, and both sign off.
+
+### The change
+
+In `Withdrawer`:
+
+```java
+@Transactional(isolation = Isolation.SERIALIZABLE)
+public long withdraw(long accountId, long amount) {
+```
+
+### After
+
+```bash
+./demo --anomaly write-skew
+```
+
+```
+ A | WithdrawalService.withdraw(1, 800)
+ A | -> attempt 1, transaction isolation level: serializable
+ A | -> funds checked: enough for 800
+ ...
+ B | -> returns -300, the new balance of account 2
+ A | -> refused, InsufficientFundsException: Cannot withdraw 800 from account 1: the customer's accounts hold 200 in total
+
+Both together: 200
+
+RESULT: OK. 1 x 800 paid out, both accounts together went from 1000 to 200. Session A passed the check, was cancelled, ran again in a new transaction and was refused.
+```
+
+Session A's first attempt was cancelled with `40001`. The retry you wrote in Task 4 caught it and
+ran A again. The second attempt read 200, and 200 is not enough for 800: a clean
+`InsufficientFundsException`. You did not have to change the retry at all.
+
+```bash
+./check 6
+./check
+```
+
+`./check` should now print 31 passes and no failures.
+
+---
+
+## Task 7: Inspect SERIALIZABLE
+
+### Step 1: nobody waits, one is cancelled
+
+```bash
+./demo --anomaly write-skew --level serializable
+```
+
+The steps are the same as at REPEATABLE READ until the end:
+
+```
+ A | commit
+ B | commit
+ B | -> ERROR, SQLSTATE 40001: could not serialize access due to read/write dependencies among transactions
+ B | -> Detail: Reason code: Canceled on identification as a pivot, during commit attempt.
+ B | -> Hint: The transaction might succeed if retried.
+```
+
+SERIALIZABLE promises: the result is the same as if the transactions had run **one after another**,
+in some order. "A then B" would have refused B. "B then A" would have refused A. Both going through
+fits neither order, so Postgres cancels one.
+
+It does not get there by running them one at a time. Both sessions read at once and both wrote at
+once. Postgres remembers **what each transaction read**, and notices that each one read something
+the other one then changed. The hint tells you what to do about it.
+
+### Step 2: the memory of what was read
+
+`./demo --anomaly write-skew --level serializable --pause` in terminal 1, `./inspect` in terminal 2:
+
+```
+SESSIONS INSIDE A TRANSACTION (snapshot_xmin is filled in while the session holds a snapshot)
+ pid session state snapshot_xmin own_xid waits_for_pid in_transaction_ms last_statement
+ ---- --------------------- ------------------- ------------- ------- ------------- ----------------- --------------------------------------------
+ 3376 demo A (serializable) idle in transaction 936 936 8944 update account set balance = balance - 800 w
+ 3377 demo B (serializable) idle in transaction 936 937 8883 update account set balance = balance - 800 w
+
+PREDICATE LOCKS (SIReadLock: what SERIALIZABLE sessions have read. They block nobody)
+ pid session relation covers page row_on_page
+ ---- --------------------- -------- -------- ---- -----------
+ 3376 demo A (serializable) account relation
+ 3377 demo B (serializable) account relation
+```
+
+- Both sessions hold a snapshot, as at REPEATABLE READ. SERIALIZABLE in Postgres is REPEATABLE READ
+ plus this tracking.
+- Each one holds a `SIReadLock` on `account`. Despite the name it is not a lock: `waits_for_pid` is
+ empty for both. It is a note that says "I read this".
+- `covers` says `relation`: the whole table. The table has two rows, so Postgres read all of it,
+ and the note covers all of it. A wider note means more transactions look like they conflict.
+ SERIALIZABLE may cancel a transaction that would have been fine. That is allowed: it must never
+ let a wrong result through, and a retry costs only time.
+
+### Step 3: a committed transaction still matters
+
+`./demo --anomaly write-skew --pause` (your application) in terminal 1, `./inspect` in terminal 2:
+
+```
+ 3445 bank-app (serializable) idle in transaction 940 ...
+
+PREDICATE LOCKS (SIReadLock: what SERIALIZABLE sessions have read. They block nobody)
+ 3445 bank-app (serializable) account relation
+ 3446 bank-app account relation
+```
+
+Session 3446 is not in the list of open transactions: it is session B, and it has committed. Its
+note is still there, because session A overlapped with it and is not finished. Postgres needs it to
+judge A.
+
+### Step 4: it can fail at COMMIT
+
+In step 1 every statement of session B worked and the **`commit`** failed. In your application's
+run the failure came earlier, at the UPDATE. Both happen. `WriteSkewIT.aFailedCommitIsAlsoCannotAcquireLockException`
+shows that Spring raises the same `CannotAcquireLockException` when the commit fails, so one `catch`
+covers both. It also means: at SERIALIZABLE, do not believe a transaction worked until the commit
+has returned.
+
+### Step 5: the level is fixed when the transaction starts
+
+`WriteSkewIT.anInnerIsolationLevelIsIgnored`: a "serializable" block that runs inside a transaction
+that is already open runs at **that** transaction's level, here `read committed`. No error, no
+warning. If a colleague calls `withdrawer.withdraw` from their own `@Transactional` method, the
+withdrawal joins their transaction and your `SERIALIZABLE` is ignored.
+
+### Step 6: everybody has to take part
+
+A READ COMMITTED transaction is not covered. Postgres only gives the guarantee among transactions
+that are all SERIALIZABLE. We ran the
+write skew with session A at SERIALIZABLE and session B at READ COMMITTED: both committed, and the
+accounts ended at -600.
+
+### What to take away
+
+- SERIALIZABLE = "as if one after another". Postgres checks it afterwards instead of making
+ transactions queue.
+- A transaction can be cancelled at any statement, including COMMIT. Always `40001`, always retry.
+- Costs: retries, some of them unnecessary, and bookkeeping for everything that is read.
+- It only works if every transaction that touches the data uses it, and if the level is set where
+ the transaction starts.
+
+---
+
+## Task 8: Compare Every Level, and Isolation Levels vs Locking
+
+### Step 1: the whole table
+
+```bash
+./demo --matrix
+```
+
+```
+Every anomaly at every isolation level: plain SQL in two sessions, 20 runs.
+
+ read-uncommitted read-committed repeatable-read serializable
+ dirty-read no no no no
+ non-repeatable-read HAPPENS HAPPENS no no
+ phantom HAPPENS HAPPENS no no
+ lost-update HAPPENS HAPPENS 40001 40001
+ write-skew HAPPENS HAPPENS HAPPENS 40001
+
+RESULT: read-uncommitted and read-committed behave the same. Levels with no anomaly left: serializable.
+```
+
+The SQL standard only says what each level **must** prevent:
+
+| SQL standard | dirty read | non-repeatable read | phantom read |
+|---|---|---|---|
+| READ UNCOMMITTED | allowed | allowed | allowed |
+| READ COMMITTED | prevented | allowed | allowed |
+| REPEATABLE READ | prevented | prevented | allowed |
+| SERIALIZABLE | prevented | prevented | prevented |
+
+Postgres is stricter in two places: READ UNCOMMITTED has no dirty reads, and REPEATABLE READ has no
+phantoms. `40001` in the output means: it did not happen, because Postgres cancelled one
+transaction. And the standard's table does not mention lost updates or write skew at all, which is
+why people who only know the table are surprised by Task 6.
+
+### Step 2: the same problem, solved with a lock
+
+```bash
+./demo --anomaly write-skew --for-update
+```
+
+```
+ A | begin isolation level read committed
+ A | select balance from account where owner = 'alice' order by id for update
+ A | -> 500, 500
+ A | # 500 + 500 = 1000, enough for 800: go ahead
+ B | begin isolation level read committed
+ B | select balance from account where owner = 'alice' order by id for update
+ B | -> WAITING. Another session holds a lock this statement needs
+ A | update account set balance = balance - 800 where id = 1
+ A | -> 1 row
+ A | commit
+ B | -> (stopped waiting) -300, 500
+ B | # -300 + 500 = 200, not enough for 800: refuse
+ B | rollback
+
+RESULT: OK. Session B had to wait for A's row locks, then read 200 and refused its withdrawal. The accounts hold 200 together.
+```
+
+The lowest useful level, and no write skew. `for update` made A's read **lock both rows**. B could
+not read them until A was finished, and then it read the truth.
+
+### Step 3: side by side
+
+| | `--for-update` (a lock) | `--level serializable` (an isolation level) |
+|---|---|---|
+| B's read | waits | returns at once, from B's snapshot |
+| Who loses | nobody is cancelled. B waits, then decides with fresh data | B is cancelled with `40001` |
+| What the code needs | nothing more | a retry |
+| Cost | B, and everyone behind it, queues while A works | wasted work, redone on retry |
+
+### Step 4: see the lock
+
+`./demo --anomaly write-skew --for-update --pause`, then `./inspect`:
+
+```
+ 1 current 500 943 944
+ 2 savings 500 943 944
+ 3523 demo A (read committed) idle in transaction 944 9029 update account set balance = balance - 800 w
+ 3525 demo B (read committed) active 944 3523 8979 select balance from account where owner = 'a
+```
+
+`waits_for_pid` says session 3525 is waiting for 3523. `xmax` of both rows is 944, which is A's
+`own_xid`: that is how Postgres marks a row as locked by transaction 944. Compare with Task 7 step
+2, where `waits_for_pid` was empty.
+
+### Step 5: what a lock cannot do
+
+"A customer may have at most 3 accounts." Two sessions each count 2 and each insert one. `SELECT ...
+FOR UPDATE` locks the rows it **returns**. The row the other session is about to insert does not
+exist yet, so there is nothing to lock. SERIALIZABLE handles it: it tracks that both sessions read
+"alice's accounts", and cancels the second one at commit with `40001`.
+
+### Isolation levels vs locking
+
+They are different tools, and interviews are full of answers that mix them up.
+
+- An **isolation level** is a setting of one transaction. It decides what that transaction may
+ **see**. Raising it adds no waiting in Postgres. When two transactions cannot both be right, one
+ is **cancelled** and has to retry.
+- A **lock** is a claim on specific rows. It makes other transactions **wait**. It works at any
+ isolation level, including the default.
+
+| Situation | Reach for |
+|---|---|
+| A report or export: several queries that must agree | REPEATABLE READ, read only. Nothing to retry, nothing to lock |
+| You will change one known row, based on its value (stock, a seat, one balance) | A lock: `SELECT ... FOR UPDATE`, or better one conditional `UPDATE`. See [`../07-locking`](../07-locking/) |
+| A rule over several rows that all exist, and conflicts are common | Lock those rows with `FOR UPDATE`, always in the same order |
+| A rule over a set of rows, or over rows that may not exist yet | SERIALIZABLE and a retry |
+
+For this project's withdrawal either tool works, because the two account rows exist and can be
+locked. The lock makes the second customer wait. SERIALIZABLE makes the second customer's request
+run twice.
+
+`./check 8` says 2 of 2 pass. They passed from the start: they pin down "a lock makes B wait" and
+"an isolation level cancels B instead".
+
+### How to say it in an interview
+
+> "The isolation level decides what a transaction can see of other transactions. Postgres defaults
+> to READ COMMITTED: every statement sees what was committed when that statement started, so two
+> queries in one transaction can disagree. That gives you non-repeatable reads and phantoms. READ
+> UNCOMMITTED exists, but Postgres runs it as READ COMMITTED, so there are no dirty reads.
+> REPEATABLE READ takes one snapshot for the whole transaction, which is what I use for a report.
+> It also stops lost updates: if I update a row that changed after my snapshot, I get SQLSTATE
+> 40001. It does not stop write skew, where two transactions read the same rows and write different
+> ones. For that I need SERIALIZABLE, which cancels one of them, again with 40001. So with either
+> of the two higher levels I need a retry, outside the transaction, with a limit. And none of this
+> is locking: a higher isolation level does not make anyone wait in Postgres, it cancels the
+> loser. If I know which row I am going to change, I would rather lock it with SELECT FOR UPDATE,
+> or do it in one UPDATE."
+
+Then be ready for the follow-ups in "Questions to Ask Afterwards" at the end of
+[`INTERVIEW_TASKS.md`](INTERVIEW_TASKS.md).
+
+---
+
+## Clean up
+
+```bash
+docker compose down
+```
diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/.mvn/jvm.config b/java/concepts/junior-mid/09-isolation-levels/solution/.mvn/jvm.config
new file mode 100644
index 0000000..07a2d88
--- /dev/null
+++ b/java/concepts/junior-mid/09-isolation-levels/solution/.mvn/jvm.config
@@ -0,0 +1,2 @@
+--enable-native-access=ALL-UNNAMED
+--sun-misc-unsafe-memory-access=allow
diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/.mvn/wrapper/maven-wrapper.properties b/java/concepts/junior-mid/09-isolation-levels/solution/.mvn/wrapper/maven-wrapper.properties
new file mode 100644
index 0000000..ffcab66
--- /dev/null
+++ b/java/concepts/junior-mid/09-isolation-levels/solution/.mvn/wrapper/maven-wrapper.properties
@@ -0,0 +1,3 @@
+wrapperVersion=3.3.4
+distributionType=only-script
+distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip
diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/check b/java/concepts/junior-mid/09-isolation-levels/solution/check
new file mode 100755
index 0000000..8a13e3b
--- /dev/null
+++ b/java/concepts/junior-mid/09-isolation-levels/solution/check
@@ -0,0 +1,4 @@
+#!/bin/sh
+# Runs on macOS and Linux. On Windows use check.cmd (type: .\check).
+cd "$(dirname "$0")" || exit 1
+exec ./mvnw -q test-compile exec:java -Dexec.mainClass=com.amigoscode.isolation.Check -Dexec.classpathScope=test -Dexec.args="$*"
diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/check.cmd b/java/concepts/junior-mid/09-isolation-levels/solution/check.cmd
new file mode 100644
index 0000000..27c9db8
--- /dev/null
+++ b/java/concepts/junior-mid/09-isolation-levels/solution/check.cmd
@@ -0,0 +1,3 @@
+@echo off
+rem Runs on Windows. On macOS and Linux use ./check
+call "%~dp0mvnw.cmd" -q -f "%~dp0pom.xml" test-compile exec:java "-Dexec.mainClass=com.amigoscode.isolation.Check" "-Dexec.classpathScope=test" "-Dexec.args=%*"
diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/compose.yaml b/java/concepts/junior-mid/09-isolation-levels/solution/compose.yaml
new file mode 100644
index 0000000..8ba5992
--- /dev/null
+++ b/java/concepts/junior-mid/09-isolation-levels/solution/compose.yaml
@@ -0,0 +1,16 @@
+name: isolation-levels
+services:
+ postgres:
+ image: postgres:17-alpine
+ container_name: isolation-levels-postgres
+ environment:
+ POSTGRES_DB: bank
+ POSTGRES_USER: bank
+ POSTGRES_PASSWORD: bank
+ ports:
+ - "5448:5432"
+ healthcheck:
+ test: ["CMD-SHELL", "pg_isready -U bank -d bank"]
+ interval: 2s
+ timeout: 2s
+ retries: 20
diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/demo b/java/concepts/junior-mid/09-isolation-levels/solution/demo
new file mode 100755
index 0000000..c68c08f
--- /dev/null
+++ b/java/concepts/junior-mid/09-isolation-levels/solution/demo
@@ -0,0 +1,4 @@
+#!/bin/sh
+# Runs on macOS and Linux. On Windows use demo.cmd (type: .\demo).
+cd "$(dirname "$0")" || exit 1
+exec ./mvnw -q compile exec:java -Dexec.mainClass=com.amigoscode.isolation.demo.Demo -Dexec.args="$*"
diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/demo.cmd b/java/concepts/junior-mid/09-isolation-levels/solution/demo.cmd
new file mode 100644
index 0000000..8b56f31
--- /dev/null
+++ b/java/concepts/junior-mid/09-isolation-levels/solution/demo.cmd
@@ -0,0 +1,3 @@
+@echo off
+rem Runs on Windows. On macOS and Linux use ./demo
+call "%~dp0mvnw.cmd" -q -f "%~dp0pom.xml" compile exec:java "-Dexec.mainClass=com.amigoscode.isolation.demo.Demo" "-Dexec.args=%*"
diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/inspect b/java/concepts/junior-mid/09-isolation-levels/solution/inspect
new file mode 100755
index 0000000..5b01fcd
--- /dev/null
+++ b/java/concepts/junior-mid/09-isolation-levels/solution/inspect
@@ -0,0 +1,4 @@
+#!/bin/sh
+# Runs on macOS and Linux. On Windows use inspect.cmd (type: .\inspect).
+cd "$(dirname "$0")" || exit 1
+exec ./mvnw -q compile exec:java -Dexec.mainClass=com.amigoscode.isolation.demo.Inspect -Dexec.args="$*"
diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/inspect.cmd b/java/concepts/junior-mid/09-isolation-levels/solution/inspect.cmd
new file mode 100644
index 0000000..550a5bb
--- /dev/null
+++ b/java/concepts/junior-mid/09-isolation-levels/solution/inspect.cmd
@@ -0,0 +1,3 @@
+@echo off
+rem Runs on Windows. On macOS and Linux use ./inspect
+call "%~dp0mvnw.cmd" -q -f "%~dp0pom.xml" compile exec:java "-Dexec.mainClass=com.amigoscode.isolation.demo.Inspect" "-Dexec.args=%*"
diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/mvnw b/java/concepts/junior-mid/09-isolation-levels/solution/mvnw
new file mode 100755
index 0000000..bd8896b
--- /dev/null
+++ b/java/concepts/junior-mid/09-isolation-levels/solution/mvnw
@@ -0,0 +1,295 @@
+#!/bin/sh
+# ----------------------------------------------------------------------------
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+# ----------------------------------------------------------------------------
+
+# ----------------------------------------------------------------------------
+# Apache Maven Wrapper startup batch script, version 3.3.4
+#
+# Optional ENV vars
+# -----------------
+# JAVA_HOME - location of a JDK home dir, required when download maven via java source
+# MVNW_REPOURL - repo url base for downloading maven distribution
+# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
+# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output
+# ----------------------------------------------------------------------------
+
+set -euf
+[ "${MVNW_VERBOSE-}" != debug ] || set -x
+
+# OS specific support.
+native_path() { printf %s\\n "$1"; }
+case "$(uname)" in
+CYGWIN* | MINGW*)
+ [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")"
+ native_path() { cygpath --path --windows "$1"; }
+ ;;
+esac
+
+# set JAVACMD and JAVACCMD
+set_java_home() {
+ # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched
+ if [ -n "${JAVA_HOME-}" ]; then
+ if [ -x "$JAVA_HOME/jre/sh/java" ]; then
+ # IBM's JDK on AIX uses strange locations for the executables
+ JAVACMD="$JAVA_HOME/jre/sh/java"
+ JAVACCMD="$JAVA_HOME/jre/sh/javac"
+ else
+ JAVACMD="$JAVA_HOME/bin/java"
+ JAVACCMD="$JAVA_HOME/bin/javac"
+
+ if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then
+ echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2
+ echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2
+ return 1
+ fi
+ fi
+ else
+ JAVACMD="$(
+ 'set' +e
+ 'unset' -f command 2>/dev/null
+ 'command' -v java
+ )" || :
+ JAVACCMD="$(
+ 'set' +e
+ 'unset' -f command 2>/dev/null
+ 'command' -v javac
+ )" || :
+
+ if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then
+ echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2
+ return 1
+ fi
+ fi
+}
+
+# hash string like Java String::hashCode
+hash_string() {
+ str="${1:-}" h=0
+ while [ -n "$str" ]; do
+ char="${str%"${str#?}"}"
+ h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296))
+ str="${str#?}"
+ done
+ printf %x\\n $h
+}
+
+verbose() { :; }
+[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; }
+
+die() {
+ printf %s\\n "$1" >&2
+ exit 1
+}
+
+trim() {
+ # MWRAPPER-139:
+ # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds.
+ # Needed for removing poorly interpreted newline sequences when running in more
+ # exotic environments such as mingw bash on Windows.
+ printf "%s" "${1}" | tr -d '[:space:]'
+}
+
+scriptDir="$(dirname "$0")"
+scriptName="$(basename "$0")"
+
+# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties
+while IFS="=" read -r key value; do
+ case "${key-}" in
+ distributionUrl) distributionUrl=$(trim "${value-}") ;;
+ distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;;
+ esac
+done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties"
+[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
+
+case "${distributionUrl##*/}" in
+maven-mvnd-*bin.*)
+ MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/
+ case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in
+ *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;;
+ :Darwin*x86_64) distributionPlatform=darwin-amd64 ;;
+ :Darwin*arm64) distributionPlatform=darwin-aarch64 ;;
+ :Linux*x86_64*) distributionPlatform=linux-amd64 ;;
+ *)
+ echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2
+ distributionPlatform=linux-amd64
+ ;;
+ esac
+ distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip"
+ ;;
+maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;;
+*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;;
+esac
+
+# apply MVNW_REPOURL and calculate MAVEN_HOME
+# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/
+[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}"
+distributionUrlName="${distributionUrl##*/}"
+distributionUrlNameMain="${distributionUrlName%.*}"
+distributionUrlNameMain="${distributionUrlNameMain%-bin}"
+MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}"
+MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")"
+
+exec_maven() {
+ unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || :
+ exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD"
+}
+
+if [ -d "$MAVEN_HOME" ]; then
+ verbose "found existing MAVEN_HOME at $MAVEN_HOME"
+ exec_maven "$@"
+fi
+
+case "${distributionUrl-}" in
+*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;;
+*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;;
+esac
+
+# prepare tmp dir
+if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then
+ clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; }
+ trap clean HUP INT TERM EXIT
+else
+ die "cannot create temp dir"
+fi
+
+mkdir -p -- "${MAVEN_HOME%/*}"
+
+# Download and Install Apache Maven
+verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
+verbose "Downloading from: $distributionUrl"
+verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
+
+# select .zip or .tar.gz
+if ! command -v unzip >/dev/null; then
+ distributionUrl="${distributionUrl%.zip}.tar.gz"
+ distributionUrlName="${distributionUrl##*/}"
+fi
+
+# verbose opt
+__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR=''
+[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v
+
+# normalize http auth
+case "${MVNW_PASSWORD:+has-password}" in
+'') MVNW_USERNAME='' MVNW_PASSWORD='' ;;
+has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;;
+esac
+
+if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then
+ verbose "Found wget ... using wget"
+ wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl"
+elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then
+ verbose "Found curl ... using curl"
+ curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl"
+elif set_java_home; then
+ verbose "Falling back to use Java to download"
+ javaSource="$TMP_DOWNLOAD_DIR/Downloader.java"
+ targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName"
+ cat >"$javaSource" <<-END
+ public class Downloader extends java.net.Authenticator
+ {
+ protected java.net.PasswordAuthentication getPasswordAuthentication()
+ {
+ return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() );
+ }
+ public static void main( String[] args ) throws Exception
+ {
+ setDefault( new Downloader() );
+ java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() );
+ }
+ }
+ END
+ # For Cygwin/MinGW, switch paths to Windows format before running javac and java
+ verbose " - Compiling Downloader.java ..."
+ "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java"
+ verbose " - Running Downloader.java ..."
+ "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")"
+fi
+
+# If specified, validate the SHA-256 sum of the Maven distribution zip file
+if [ -n "${distributionSha256Sum-}" ]; then
+ distributionSha256Result=false
+ if [ "$MVN_CMD" = mvnd.sh ]; then
+ echo "Checksum validation is not supported for maven-mvnd." >&2
+ echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
+ exit 1
+ elif command -v sha256sum >/dev/null; then
+ if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then
+ distributionSha256Result=true
+ fi
+ elif command -v shasum >/dev/null; then
+ if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then
+ distributionSha256Result=true
+ fi
+ else
+ echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2
+ echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
+ exit 1
+ fi
+ if [ $distributionSha256Result = false ]; then
+ echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2
+ echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2
+ exit 1
+ fi
+fi
+
+# unzip and move
+if command -v unzip >/dev/null; then
+ unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip"
+else
+ tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar"
+fi
+
+# Find the actual extracted directory name (handles snapshots where filename != directory name)
+actualDistributionDir=""
+
+# First try the expected directory name (for regular distributions)
+if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then
+ if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then
+ actualDistributionDir="$distributionUrlNameMain"
+ fi
+fi
+
+# If not found, search for any directory with the Maven executable (for snapshots)
+if [ -z "$actualDistributionDir" ]; then
+ # enable globbing to iterate over items
+ set +f
+ for dir in "$TMP_DOWNLOAD_DIR"/*; do
+ if [ -d "$dir" ]; then
+ if [ -f "$dir/bin/$MVN_CMD" ]; then
+ actualDistributionDir="$(basename "$dir")"
+ break
+ fi
+ fi
+ done
+ set -f
+fi
+
+if [ -z "$actualDistributionDir" ]; then
+ verbose "Contents of $TMP_DOWNLOAD_DIR:"
+ verbose "$(ls -la "$TMP_DOWNLOAD_DIR")"
+ die "Could not find Maven distribution directory in extracted archive"
+fi
+
+verbose "Found extracted Maven distribution directory: $actualDistributionDir"
+printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url"
+mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME"
+
+clean || :
+exec_maven "$@"
diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/mvnw.cmd b/java/concepts/junior-mid/09-isolation-levels/solution/mvnw.cmd
new file mode 100644
index 0000000..92450f9
--- /dev/null
+++ b/java/concepts/junior-mid/09-isolation-levels/solution/mvnw.cmd
@@ -0,0 +1,189 @@
+<# : batch portion
+@REM ----------------------------------------------------------------------------
+@REM Licensed to the Apache Software Foundation (ASF) under one
+@REM or more contributor license agreements. See the NOTICE file
+@REM distributed with this work for additional information
+@REM regarding copyright ownership. The ASF licenses this file
+@REM to you under the Apache License, Version 2.0 (the
+@REM "License"); you may not use this file except in compliance
+@REM with the License. You may obtain a copy of the License at
+@REM
+@REM http://www.apache.org/licenses/LICENSE-2.0
+@REM
+@REM Unless required by applicable law or agreed to in writing,
+@REM software distributed under the License is distributed on an
+@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+@REM KIND, either express or implied. See the License for the
+@REM specific language governing permissions and limitations
+@REM under the License.
+@REM ----------------------------------------------------------------------------
+
+@REM ----------------------------------------------------------------------------
+@REM Apache Maven Wrapper startup batch script, version 3.3.4
+@REM
+@REM Optional ENV vars
+@REM MVNW_REPOURL - repo url base for downloading maven distribution
+@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
+@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output
+@REM ----------------------------------------------------------------------------
+
+@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0)
+@SET __MVNW_CMD__=
+@SET __MVNW_ERROR__=
+@SET __MVNW_PSMODULEP_SAVE=%PSModulePath%
+@SET PSModulePath=
+@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @(
+ IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B)
+)
+@SET PSModulePath=%__MVNW_PSMODULEP_SAVE%
+@SET __MVNW_PSMODULEP_SAVE=
+@SET __MVNW_ARG0_NAME__=
+@SET MVNW_USERNAME=
+@SET MVNW_PASSWORD=
+@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*)
+@echo Cannot start maven from wrapper >&2 && exit /b 1
+@GOTO :EOF
+: end batch / begin powershell #>
+
+$ErrorActionPreference = "Stop"
+if ($env:MVNW_VERBOSE -eq "true") {
+ $VerbosePreference = "Continue"
+}
+
+# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties
+$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl
+if (!$distributionUrl) {
+ Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
+}
+
+switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) {
+ "maven-mvnd-*" {
+ $USE_MVND = $true
+ $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip"
+ $MVN_CMD = "mvnd.cmd"
+ break
+ }
+ default {
+ $USE_MVND = $false
+ $MVN_CMD = $script -replace '^mvnw','mvn'
+ break
+ }
+}
+
+# apply MVNW_REPOURL and calculate MAVEN_HOME
+# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/
+if ($env:MVNW_REPOURL) {
+ $MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" }
+ $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')"
+}
+$distributionUrlName = $distributionUrl -replace '^.*/',''
+$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$',''
+
+$MAVEN_M2_PATH = "$HOME/.m2"
+if ($env:MAVEN_USER_HOME) {
+ $MAVEN_M2_PATH = "$env:MAVEN_USER_HOME"
+}
+
+if (-not (Test-Path -Path $MAVEN_M2_PATH)) {
+ New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null
+}
+
+$MAVEN_WRAPPER_DISTS = $null
+if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) {
+ $MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists"
+} else {
+ $MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists"
+}
+
+$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain"
+$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join ''
+$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME"
+
+if (Test-Path -Path "$MAVEN_HOME" -PathType Container) {
+ Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME"
+ Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
+ exit $?
+}
+
+if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) {
+ Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl"
+}
+
+# prepare tmp dir
+$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile
+$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir"
+$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null
+trap {
+ if ($TMP_DOWNLOAD_DIR.Exists) {
+ try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
+ catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
+ }
+}
+
+New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null
+
+# Download and Install Apache Maven
+Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
+Write-Verbose "Downloading from: $distributionUrl"
+Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
+
+$webclient = New-Object System.Net.WebClient
+if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) {
+ $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD)
+}
+[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
+$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null
+
+# If specified, validate the SHA-256 sum of the Maven distribution zip file
+$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum
+if ($distributionSha256Sum) {
+ if ($USE_MVND) {
+ Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties."
+ }
+ Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash
+ if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) {
+ Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property."
+ }
+}
+
+# unzip and move
+Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null
+
+# Find the actual extracted directory name (handles snapshots where filename != directory name)
+$actualDistributionDir = ""
+
+# First try the expected directory name (for regular distributions)
+$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain"
+$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD"
+if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) {
+ $actualDistributionDir = $distributionUrlNameMain
+}
+
+# If not found, search for any directory with the Maven executable (for snapshots)
+if (!$actualDistributionDir) {
+ Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object {
+ $testPath = Join-Path $_.FullName "bin/$MVN_CMD"
+ if (Test-Path -Path $testPath -PathType Leaf) {
+ $actualDistributionDir = $_.Name
+ }
+ }
+}
+
+if (!$actualDistributionDir) {
+ Write-Error "Could not find Maven distribution directory in extracted archive"
+}
+
+Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir"
+Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null
+try {
+ Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null
+} catch {
+ if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) {
+ Write-Error "fail to move MAVEN_HOME"
+ }
+} finally {
+ try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
+ catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
+}
+
+Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/pom.xml b/java/concepts/junior-mid/09-isolation-levels/solution/pom.xml
new file mode 100644
index 0000000..f773e9e
--- /dev/null
+++ b/java/concepts/junior-mid/09-isolation-levels/solution/pom.xml
@@ -0,0 +1,101 @@
+
+
+ 4.0.0
+
+
+ org.springframework.boot
+ spring-boot-starter-parent
+ 4.0.2
+
+
+
+ com.amigoscode
+ isolation-levels
+ 0.0.1-SNAPSHOT
+ isolation-levels
+ Transaction isolation levels: see the anomalies, then fix them with the right level and a retry
+
+
+ 25
+ 3.5.0
+
+
+
+
+ org.springframework.boot
+ spring-boot-starter-data-jpa
+
+
+ org.postgresql
+ postgresql
+ runtime
+
+
+
+
+ org.springframework.boot
+ spring-boot-starter-test
+ test
+
+
+ org.mockito
+ mockito-core
+
+
+ org.mockito
+ mockito-junit-jupiter
+
+
+
+
+ org.springframework.boot
+ spring-boot-starter-data-jpa-test
+ test
+
+
+ org.testcontainers
+ testcontainers-postgresql
+ test
+
+
+ org.junit.platform
+ junit-platform-launcher
+ test
+
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+
+
+ org.apache.maven.plugins
+ maven-failsafe-plugin
+
+
+
+ integration-test
+ verify
+
+
+
+
+
+
+ org.codehaus.mojo
+ exec-maven-plugin
+ ${exec-maven-plugin.version}
+
+ false
+
+
+
+
+
+
diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/IsolationApplication.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/IsolationApplication.java
new file mode 100644
index 0000000..80b534d
--- /dev/null
+++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/IsolationApplication.java
@@ -0,0 +1,12 @@
+package com.amigoscode.isolation;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+@SpringBootApplication
+public class IsolationApplication {
+
+ public static void main(String[] args) {
+ SpringApplication.run(IsolationApplication.class, args);
+ }
+}
diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/account/Account.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/account/Account.java
new file mode 100644
index 0000000..83d91c8
--- /dev/null
+++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/account/Account.java
@@ -0,0 +1,49 @@
+package com.amigoscode.isolation.account;
+
+import jakarta.persistence.Entity;
+import jakarta.persistence.Id;
+import jakarta.persistence.Table;
+
+@Entity
+@Table(name = "account")
+public class Account {
+
+ @Id
+ private Long id;
+
+ private String owner;
+
+ private String name;
+
+ private long balance;
+
+ protected Account() {
+ }
+
+ public Account(long id, String owner, String name, long balance) {
+ this.id = id;
+ this.owner = owner;
+ this.name = name;
+ this.balance = balance;
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public String getOwner() {
+ return owner;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public long getBalance() {
+ return balance;
+ }
+
+ public void setBalance(long balance) {
+ this.balance = balance;
+ }
+}
diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/account/AccountNotFoundException.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/account/AccountNotFoundException.java
new file mode 100644
index 0000000..73df1c2
--- /dev/null
+++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/account/AccountNotFoundException.java
@@ -0,0 +1,8 @@
+package com.amigoscode.isolation.account;
+
+public class AccountNotFoundException extends RuntimeException {
+
+ public AccountNotFoundException(long accountId) {
+ super("Account " + accountId + " does not exist");
+ }
+}
diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/account/AccountRepository.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/account/AccountRepository.java
new file mode 100644
index 0000000..b614f2e
--- /dev/null
+++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/account/AccountRepository.java
@@ -0,0 +1,16 @@
+package com.amigoscode.isolation.account;
+
+import java.util.List;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.Query;
+import org.springframework.data.repository.query.Param;
+
+public interface AccountRepository extends JpaRepository {
+
+ List findByOwnerOrderById(String owner);
+
+ long countByOwner(String owner);
+
+ @Query("select coalesce(sum(a.balance), 0) from Account a where a.owner = :owner")
+ long totalBalance(@Param("owner") String owner);
+}
diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/checkpoint/Checkpoint.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/checkpoint/Checkpoint.java
new file mode 100644
index 0000000..f3fa680
--- /dev/null
+++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/checkpoint/Checkpoint.java
@@ -0,0 +1,18 @@
+package com.amigoscode.isolation.checkpoint;
+
+/**
+ * A named point in the middle of a transaction, between a READ and what the code does with it.
+ * In production nothing happens here. The demo and the tests use it to let a second session do
+ * its work at exactly this moment, so the dangerous interleaving happens every time instead of
+ * once a month.
+ */
+public interface Checkpoint {
+
+ /** StatementService has read the lines and is about to read the total. */
+ String LINES_READ = "statement: lines read";
+
+ /** Withdrawer has checked the funds and is about to write the new balance. */
+ String FUNDS_CHECKED = "withdrawal: funds checked";
+
+ void reached(String name);
+}
diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/checkpoint/NoCheckpoint.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/checkpoint/NoCheckpoint.java
new file mode 100644
index 0000000..68c9ab0
--- /dev/null
+++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/checkpoint/NoCheckpoint.java
@@ -0,0 +1,12 @@
+package com.amigoscode.isolation.checkpoint;
+
+import org.springframework.stereotype.Component;
+
+/** What runs in production: nothing. */
+@Component
+public class NoCheckpoint implements Checkpoint {
+
+ @Override
+ public void reached(String name) {
+ }
+}
diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/checkpoint/ScriptedCheckpoint.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/checkpoint/ScriptedCheckpoint.java
new file mode 100644
index 0000000..9ffa0e1
--- /dev/null
+++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/checkpoint/ScriptedCheckpoint.java
@@ -0,0 +1,52 @@
+package com.amigoscode.isolation.checkpoint;
+
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.IntConsumer;
+
+/**
+ * Used by the demo and the tests instead of {@link NoCheckpoint}: runs an action whenever a
+ * checkpoint is reached, on the thread that reached it, which means in the middle of that
+ * thread's transaction.
+ */
+public final class ScriptedCheckpoint implements Checkpoint {
+
+ private final Map arrivals = new ConcurrentHashMap<>();
+ private final Map actions = new ConcurrentHashMap<>();
+
+ /** Forget every action and every count. */
+ public void reset() {
+ arrivals.clear();
+ actions.clear();
+ }
+
+ /** Runs {@code action} every time {@code name} is reached. It receives the arrival number: 1, 2, 3... */
+ public void onReached(String name, IntConsumer action) {
+ actions.put(name, action);
+ }
+
+ /** Runs {@code action} the first time {@code name} is reached, and never again (so not on a retry). */
+ public void onFirst(String name, Runnable action) {
+ onReached(name, arrival -> {
+ if (arrival == 1) {
+ action.run();
+ }
+ });
+ }
+
+ /** How many times {@code name} has been reached. */
+ public int arrivals(String name) {
+ AtomicInteger count = arrivals.get(name);
+ return count == null ? 0 : count.get();
+ }
+
+ @Override
+ public void reached(String name) {
+ int arrival = arrivals.computeIfAbsent(name, key -> new AtomicInteger()).incrementAndGet();
+ IntConsumer action = actions.get(name);
+ if (action != null) {
+ action.accept(arrival);
+ }
+ }
+}
diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/Anomaly.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/Anomaly.java
new file mode 100644
index 0000000..de1cf63
--- /dev/null
+++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/Anomaly.java
@@ -0,0 +1,24 @@
+package com.amigoscode.isolation.demo;
+
+import java.util.Arrays;
+import java.util.Locale;
+import java.util.stream.Collectors;
+
+/** The things that can go wrong when two transactions overlap. */
+public enum Anomaly {
+ DIRTY_READ, NON_REPEATABLE_READ, PHANTOM, LOST_UPDATE, WRITE_SKEW;
+
+ /** As written on the command line: "write-skew". */
+ public String flag() {
+ return name().toLowerCase(Locale.ROOT).replace('_', '-');
+ }
+
+ static Anomaly from(String value) {
+ return Arrays.stream(values()).filter(anomaly -> anomaly.flag().equals(value)).findFirst()
+ .orElseThrow(() -> new IllegalArgumentException("Unknown anomaly: " + value + ". Use one of: " + names()));
+ }
+
+ static String names() {
+ return Arrays.stream(values()).map(Anomaly::flag).collect(Collectors.joining(" | "));
+ }
+}
diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/AppDemo.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/AppDemo.java
new file mode 100644
index 0000000..0452b2f
--- /dev/null
+++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/AppDemo.java
@@ -0,0 +1,220 @@
+package com.amigoscode.isolation.demo;
+
+import com.amigoscode.isolation.IsolationApplication;
+import com.amigoscode.isolation.checkpoint.Checkpoint;
+import com.amigoscode.isolation.checkpoint.ScriptedCheckpoint;
+import com.amigoscode.isolation.statement.Statement;
+import com.amigoscode.isolation.statement.StatementService;
+import com.amigoscode.isolation.withdrawal.InsufficientFundsException;
+import com.amigoscode.isolation.withdrawal.WithdrawalService;
+import java.sql.Connection;
+import java.sql.SQLException;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import org.springframework.boot.Banner;
+import org.springframework.boot.SpringApplication;
+import org.springframework.context.ConfigurableApplicationContext;
+import org.springframework.context.support.GenericApplicationContext;
+import org.springframework.jdbc.core.JdbcTemplate;
+
+/**
+ * Runs the application's own code (StatementService, WithdrawalService) as session A, and makes a
+ * second session do its work at a checkpoint in the middle of A's transaction. What you see depends
+ * on the @Transactional settings in the code.
+ */
+final class AppDemo {
+
+ private final ConfigurableApplicationContext context;
+ private final ScriptedCheckpoint checkpoint;
+ private final JdbcTemplate jdbc;
+ private final Timeline timeline = new Timeline(System.out);
+ private final int pauseSeconds;
+
+ private AppDemo(ConfigurableApplicationContext context, ScriptedCheckpoint checkpoint, int pauseSeconds) {
+ this.context = context;
+ this.checkpoint = checkpoint;
+ this.jdbc = context.getBean(JdbcTemplate.class);
+ this.pauseSeconds = pauseSeconds;
+ }
+
+ static void run(Anomaly anomaly, int pauseSeconds) throws SQLException {
+ ScriptedCheckpoint checkpoint = new ScriptedCheckpoint();
+ SpringApplication app = new SpringApplication(IsolationApplication.class);
+ app.setBannerMode(Banner.Mode.OFF);
+ app.setLogStartupInfo(false);
+ // The demo's checkpoint replaces the one that does nothing.
+ app.addInitializers(context -> ((GenericApplicationContext) context).registerBean(
+ "demoCheckpoint", ScriptedCheckpoint.class, () -> checkpoint, bean -> bean.setPrimary(true)));
+ try (ConfigurableApplicationContext context = app.run(
+ "--logging.level.root=WARN",
+ // A cancelled transaction is shown as one line in the timeline instead of a log entry.
+ "--logging.level.org.hibernate.orm.jdbc.error=OFF")) {
+ try (Connection connection = Db.connect()) {
+ Db.reset(connection);
+ }
+ AppDemo demo = new AppDemo(context, checkpoint, pauseSeconds);
+ System.out.println();
+ switch (anomaly) {
+ case NON_REPEATABLE_READ, PHANTOM -> demo.statement(anomaly);
+ case LOST_UPDATE -> demo.withdrawals(anomaly, 1, 1, 100);
+ case WRITE_SKEW -> demo.withdrawals(anomaly, 1, 2, 800);
+ case DIRTY_READ -> throw new IllegalStateException("dirty-read is always plain SQL");
+ }
+ System.out.println();
+ }
+ }
+
+ /** Session A is StatementService.statement. Session B commits a change between A's queries. */
+ private void statement(Anomaly anomaly) throws SQLException {
+ System.out.println("Anomaly: " + anomaly.flag() + " | running the application: StatementService.statement");
+ System.out.println("Session A is the application, building alice's statement: the lines first, then the count and the total.");
+ System.out.println(anomaly == Anomaly.PHANTOM
+ ? "Session B opens a new account for alice and commits in between."
+ : "Session B deposits 100 and commits in between.");
+ System.out.println("Before: alice has two accounts, current (id 1) = 500 and savings (id 2) = 500.");
+ System.out.println();
+
+ Statement statement;
+ try (Connection monitor = Db.connect(); Session b = new Session("B", Db.connect(), monitor, timeline)) {
+ checkpoint.onFirst(Checkpoint.LINES_READ, () -> {
+ timeline.result("A", "transaction isolation level: " + levelOfThisTransaction());
+ timeline.result("A", "query 1 done: the lines are read");
+ b.exec("begin");
+ b.exec(anomaly == Anomaly.PHANTOM
+ ? "insert into account (id, owner, name, balance) values (3, 'alice', 'holiday', 250)"
+ : "update account set balance = balance + 100 where id = 1");
+ b.exec("commit");
+ pause();
+ });
+ timeline.step("A", "StatementService.statement(\"alice\")");
+ statement = context.getBean(StatementService.class).statement("alice");
+ timeline.result("A", "queries 2 and 3 done: the count and the total are read");
+ }
+
+ System.out.println();
+ System.out.println("The statement the customer gets:");
+ for (Statement.Line line : statement.lines()) {
+ System.out.printf(" %-12s %6d%n", line.account(), line.balance());
+ }
+ System.out.println(" -------------------");
+ System.out.printf(" %-12s %6d%n", statement.accountCount() + " accounts", statement.total());
+ System.out.println();
+ if (statement.addsUp()) {
+ System.out.println("RESULT: OK. " + statement.lines().size() + " lines, " + statement.accountCount()
+ + " accounts, and the lines add up to the total: " + statement.total()
+ + ". What session B committed is not in this statement. It will be in the next one.");
+ } else if (statement.lines().size() != statement.accountCount()) {
+ System.out.println("RESULT: PHANTOM READ. The statement lists " + statement.lines().size()
+ + " accounts and then says there are " + statement.accountCount() + ". The lines add up to "
+ + statement.sumOfLines() + ", the total says " + statement.total() + ".");
+ } else {
+ System.out.println("RESULT: NON-REPEATABLE READ. The lines add up to " + statement.sumOfLines()
+ + ", the total says " + statement.total() + ". The queries of one transaction saw two different moments.");
+ }
+ }
+
+ /** Session A and session B are both WithdrawalService.withdraw. B runs while A is between its check and its write. */
+ private void withdrawals(Anomaly anomaly, long accountA, long accountB, long amount) {
+ System.out.println("Anomaly: " + anomaly.flag() + " | running the application: WithdrawalService.withdraw");
+ System.out.println(Demo.story(anomaly));
+ System.out.println("Session B does all of its work while A is between checking the funds and writing the new balance.");
+ System.out.println("Before: alice has two accounts, current (id 1) = 500 and savings (id 2) = 500.");
+ System.out.println();
+
+ Thread sessionA = Thread.currentThread();
+ Map attempts = new ConcurrentHashMap<>();
+ Map thrown = new ConcurrentHashMap<>();
+ Map paidOut = new ConcurrentHashMap<>();
+ checkpoint.onReached(Checkpoint.FUNDS_CHECKED, arrival -> {
+ String session = Thread.currentThread() == sessionA ? "A" : "B";
+ int attempt = attempts.merge(session, 1, Integer::sum);
+ timeline.result(session, "attempt " + attempt + (attempt > 1 ? " (a new transaction: the last one did not commit)" : "")
+ + ", transaction isolation level: " + levelOfThisTransaction());
+ timeline.result(session, "funds checked: enough for " + amount);
+ if (session.equals("A") && attempt == 1) {
+ Thread sessionB = new Thread(() -> withdraw("B", accountB, amount, thrown, paidOut), "session-B");
+ sessionB.start();
+ try {
+ sessionB.join();
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ pause();
+ }
+ });
+ withdraw("A", accountA, amount, thrown, paidOut);
+
+ long current = jdbc.queryForObject("select balance from account where id = 1", Long.class);
+ long savings = jdbc.queryForObject("select balance from account where id = 2", Long.class);
+ System.out.println();
+ System.out.println("Withdrawals paid out: " + paidOut.size() + " x " + amount);
+ System.out.println("Current (id 1): " + current);
+ System.out.println("Savings (id 2): " + savings);
+ System.out.println("Both together: " + (current + savings));
+ System.out.println();
+
+ if (!thrown.isEmpty()) {
+ String session = thrown.keySet().iterator().next();
+ System.out.println("RESULT: NOT HANDLED. The data is right, because Postgres cancelled session " + session
+ + "'s transaction. But the customer got a " + thrown.get(session).getClass().getSimpleName()
+ + ". Nothing was wrong with the request: it has to be run again.");
+ } else if (anomaly == Anomaly.LOST_UPDATE && current != 500 - paidOut.size() * amount) {
+ System.out.println("RESULT: LOST UPDATE. " + paidOut.size() + " withdrawals of " + amount
+ + " were paid out, but the balance only went from 500 to " + current + ".");
+ } else if (current + savings < 0) {
+ System.out.println("RESULT: WRITE SKEW. Both withdrawals of " + amount + " went through and the accounts hold "
+ + (current + savings) + " together. The rule is broken, and neither transaction changed a row the other one changed.");
+ } else {
+ System.out.println("RESULT: OK. " + paidOut.size() + " x " + amount + " paid out, both accounts together went from 1000 to "
+ + (current + savings) + "." + (attempts.getOrDefault("A", 1) > 1
+ ? " Session A was cancelled once and ran again in a new transaction."
+ : !paidOut.containsKey("A")
+ ? " Session A passed the check, was cancelled, ran again in a new transaction and was refused."
+ : ""));
+ }
+ }
+
+ private void withdraw(String session, long accountId, long amount, Map thrown,
+ Map paidOut) {
+ timeline.step(session, "WithdrawalService.withdraw(" + accountId + ", " + amount + ")");
+ try {
+ long newBalance = context.getBean(WithdrawalService.class).withdraw(accountId, amount);
+ paidOut.put(session, true);
+ timeline.result(session, "returns " + newBalance + ", the new balance of account " + accountId);
+ } catch (InsufficientFundsException e) {
+ timeline.result(session, "refused, InsufficientFundsException: " + e.getMessage());
+ } catch (RuntimeException e) {
+ thrown.put(session, e);
+ timeline.result(session, "THROWS " + e.getClass().getName());
+ Throwable root = e;
+ while (root.getCause() != null) {
+ root = root.getCause();
+ }
+ String message = String.valueOf(root.getMessage()).lines().findFirst().orElse("");
+ timeline.result(session, "caused by " + root.getClass().getSimpleName()
+ + (root instanceof SQLException sql ? ", SQLSTATE " + sql.getSQLState() : "") + ": " + message);
+ }
+ }
+
+ /**
+ * Asked on the calling thread, so it runs inside that thread's transaction, on its connection.
+ * The session also puts the level into its application_name, where ./inspect can read it:
+ * Postgres has no column that shows another session's isolation level.
+ */
+ private String levelOfThisTransaction() {
+ String level = jdbc.queryForObject("show transaction_isolation", String.class);
+ jdbc.execute("set local application_name = 'bank-app (" + level + ")'");
+ return level;
+ }
+
+ private void pause() {
+ if (pauseSeconds > 0) {
+ timeline.note("Paused for " + pauseSeconds + " seconds. Run ./inspect in another terminal now.");
+ try {
+ Thread.sleep(pauseSeconds * 1000L);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ }
+ }
+}
diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/Db.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/Db.java
new file mode 100644
index 0000000..7779e2a
--- /dev/null
+++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/Db.java
@@ -0,0 +1,63 @@
+package com.amigoscode.isolation.demo;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.charset.StandardCharsets;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.SQLException;
+import java.sql.Statement;
+
+/** Connection settings shared by the demo and inspect tools. Same defaults as application.properties. */
+public final class Db {
+
+ static final String URL = env("DB_URL", "jdbc:postgresql://localhost:5448/bank");
+ static final String USER = env("DB_USER", "bank");
+ static final String PASSWORD = env("DB_PASSWORD", "bank");
+
+ private Db() {
+ }
+
+ static Connection connect() throws SQLException {
+ return DriverManager.getConnection(URL, USER, PASSWORD);
+ }
+
+ /** Returns false, after printing what to do, when Postgres is not reachable. */
+ static boolean isUp() {
+ try (Connection ignored = connect()) {
+ return true;
+ } catch (SQLException e) {
+ System.out.println();
+ System.out.println("Cannot reach Postgres at " + URL);
+ System.out.println("Start it first, from this folder:");
+ System.out.println();
+ System.out.println(" docker compose up -d");
+ System.out.println();
+ System.out.println("(" + e.getMessage().lines().findFirst().orElse("") + ")");
+ return false;
+ }
+ }
+
+ /** Creates the table if needed and puts the data back: alice, current 500 and savings 500. */
+ public static void reset(Connection connection) throws SQLException {
+ try (Statement statement = connection.createStatement()) {
+ statement.execute(schema());
+ statement.execute("delete from account");
+ statement.execute("insert into account (id, owner, name, balance) "
+ + "values (1, 'alice', 'current', 500), (2, 'alice', 'savings', 500)");
+ }
+ }
+
+ private static String schema() {
+ try (InputStream in = Db.class.getResourceAsStream("/schema.sql")) {
+ return new String(in.readAllBytes(), StandardCharsets.UTF_8);
+ } catch (IOException e) {
+ throw new IllegalStateException("Cannot read schema.sql", e);
+ }
+ }
+
+ private static String env(String name, String fallback) {
+ String value = System.getenv(name);
+ return value == null || value.isBlank() ? fallback : value;
+ }
+}
diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/Demo.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/Demo.java
new file mode 100644
index 0000000..76b74db
--- /dev/null
+++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/Demo.java
@@ -0,0 +1,184 @@
+package com.amigoscode.isolation.demo;
+
+import com.amigoscode.isolation.demo.Outcome.Verdict;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Two sessions, one fixed order of steps, printed as a timeline that ends in a RESULT line.
+ * Without --level it runs the application's own code. With --level it runs the same anomaly as
+ * plain SQL at the level you choose. Run it with ./demo (or .\demo on Windows). ./demo --help
+ * lists the flags.
+ */
+public final class Demo {
+
+ static final int PAUSE_SECONDS = 15;
+
+ private record Options(Anomaly anomaly, Level level, boolean matrix, boolean forUpdate, boolean pause) {
+ }
+
+ public static void main(String[] args) throws Exception {
+ Options options;
+ try {
+ options = parse(args);
+ } catch (IllegalArgumentException e) {
+ System.out.println(e.getMessage());
+ System.out.println();
+ printHelp();
+ return;
+ }
+ if (options == null) {
+ printHelp();
+ return;
+ }
+ if (!Db.isUp()) {
+ return;
+ }
+ if (options.matrix()) {
+ matrix();
+ } else if (options.level() != null) {
+ sql(options);
+ } else {
+ AppDemo.run(options.anomaly(), options.pause() ? PAUSE_SECONDS : 0);
+ }
+ }
+
+ /** One anomaly as plain SQL at one level. */
+ private static void sql(Options options) {
+ System.out.println();
+ System.out.println("Anomaly: " + options.anomaly().flag() + " | level: " + options.level().sql()
+ + (options.forUpdate() ? " + SELECT ... FOR UPDATE" : "") + " | plain SQL in two sessions");
+ System.out.println(story(options.anomaly()));
+ System.out.println("Before: alice has two accounts, current (id 1) = 500 and savings (id 2) = 500.");
+ System.out.println();
+ Lab lab = new Lab(Db.URL, Db.USER, Db.PASSWORD, System.out);
+ Outcome outcome = lab.run(options.anomaly(), options.level(),
+ new Lab.Options(options.forUpdate(), options.pause() ? PAUSE_SECONDS : 0));
+ System.out.println();
+ System.out.println("RESULT: " + outcome.result());
+ System.out.println();
+ }
+
+ static String story(Anomaly anomaly) {
+ return switch (anomaly) {
+ case DIRTY_READ -> "Session B changes a balance and has NOT committed. Session A reads that balance.";
+ case NON_REPEATABLE_READ -> "Session A reads one balance twice. Session B deposits 100 and commits in between.";
+ case PHANTOM -> "Session A counts alice's accounts twice. Session B opens a new account and commits in between.";
+ case LOST_UPDATE -> "Both sessions withdraw 100 from account 1: read the balance, subtract, write it back.";
+ case WRITE_SKEW -> "A withdraws 800 from account 1, B withdraws 800 from account 2. "
+ + "The rule: both accounts together must stay at 0 or above.";
+ };
+ }
+
+ /** Every anomaly at every level. */
+ private static void matrix() {
+ Lab lab = new Lab(Db.URL, Db.USER, Db.PASSWORD, null);
+ System.out.println();
+ System.out.println("Every anomaly at every isolation level: plain SQL in two sessions, "
+ + Anomaly.values().length * Level.values().length + " runs.");
+ System.out.println();
+ StringBuilder header = new StringBuilder(String.format(" %-21s", ""));
+ for (Level level : Level.values()) {
+ header.append(String.format("%-18s", level.flag()));
+ }
+ System.out.println(header.toString().stripTrailing());
+ List> columns = new ArrayList<>();
+ for (Level ignored : Level.values()) {
+ columns.add(new ArrayList<>());
+ }
+ for (Anomaly anomaly : Anomaly.values()) {
+ StringBuilder row = new StringBuilder(String.format(" %-21s", anomaly.flag()));
+ for (Level level : Level.values()) {
+ Outcome outcome = lab.run(anomaly, level);
+ String cell = outcome.verdict() == Verdict.HAPPENED ? "HAPPENS"
+ : outcome.verdict() == Verdict.SERIALIZATION_FAILURE ? outcome.sqlState() : "no";
+ columns.get(level.ordinal()).add(cell);
+ row.append(String.format("%-18s", cell));
+ }
+ System.out.println(row.toString().stripTrailing());
+ }
+ System.out.println();
+ System.out.println(" HAPPENS = the anomaly happened and nobody was told");
+ System.out.println(" no = it did not happen");
+ System.out.println(" 40001 = it did not happen, because Postgres cancelled one transaction with");
+ System.out.println(" SQLSTATE 40001 (serialization failure). The application has to retry it");
+ System.out.println();
+ boolean sameAsReadCommitted = columns.get(Level.READ_UNCOMMITTED.ordinal())
+ .equals(columns.get(Level.READ_COMMITTED.ordinal()));
+ List clean = new ArrayList<>();
+ for (Level level : Level.values()) {
+ if (!columns.get(level.ordinal()).contains("HAPPENS")) {
+ clean.add(level.flag());
+ }
+ }
+ System.out.println("RESULT: read-uncommitted and read-committed "
+ + (sameAsReadCommitted ? "behave the same" : "DIFFER") + ". Levels with no anomaly left: "
+ + (clean.isEmpty() ? "none" : String.join(", ", clean)) + ".");
+ System.out.println();
+ }
+
+ private static Options parse(String[] args) {
+ Anomaly anomaly = Anomaly.NON_REPEATABLE_READ;
+ Level level = null;
+ boolean matrix = false;
+ boolean forUpdate = false;
+ boolean pause = false;
+ for (int i = 0; i < args.length; i++) {
+ String arg = args[i];
+ switch (arg) {
+ case "--help", "-h" -> {
+ return null;
+ }
+ case "--anomaly" -> anomaly = Anomaly.from(value(args, ++i, arg));
+ case "--level" -> level = Level.from(value(args, ++i, arg));
+ case "--matrix" -> matrix = true;
+ case "--for-update" -> forUpdate = true;
+ case "--pause" -> pause = true;
+ default -> throw new IllegalArgumentException("Unknown option: " + arg);
+ }
+ }
+ if (forUpdate && anomaly != Anomaly.WRITE_SKEW) {
+ throw new IllegalArgumentException("--for-update only works with --anomaly write-skew");
+ }
+ if (level == null && forUpdate) {
+ level = Level.READ_COMMITTED;
+ }
+ if (level == null && anomaly == Anomaly.DIRTY_READ) {
+ // The application has no code that could show a dirty read, so this one is always plain SQL.
+ level = Level.READ_UNCOMMITTED;
+ }
+ return new Options(anomaly, level, matrix, forUpdate, pause);
+ }
+
+ private static String value(String[] args, int index, String option) {
+ if (index >= args.length) {
+ throw new IllegalArgumentException(option + " needs a value");
+ }
+ return args[index];
+ }
+
+ private static void printHelp() {
+ System.out.println("Usage: ./demo [options] (Windows: .\\demo [options])");
+ System.out.println();
+ System.out.println(" --anomaly " + Anomaly.names());
+ System.out.println(" (default: non-repeatable-read)");
+ System.out.println(" --level " + Level.names());
+ System.out.println(" Runs the anomaly as plain SQL at this level.");
+ System.out.println(" Without --level the demo runs the APPLICATION's code, so it shows");
+ System.out.println(" what your @Transactional settings do. (dirty-read is always plain SQL.)");
+ System.out.println(" --for-update write-skew only, plain SQL: the read locks the rows (SELECT ... FOR UPDATE)");
+ System.out.println(" --matrix every anomaly at every level, as one table");
+ System.out.println(" --pause hold the transactions open for " + PAUSE_SECONDS
+ + " seconds in the middle, so you can run ./inspect");
+ System.out.println();
+ System.out.println("Examples:");
+ System.out.println(" ./demo");
+ System.out.println(" ./demo --anomaly phantom");
+ System.out.println(" ./demo --anomaly write-skew --level serializable");
+ System.out.println(" ./demo --anomaly dirty-read --level read-uncommitted");
+ System.out.println(" ./demo --matrix");
+ }
+
+ private Demo() {
+ }
+}
diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/Inspect.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/Inspect.java
new file mode 100644
index 0000000..da14cb3
--- /dev/null
+++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/Inspect.java
@@ -0,0 +1,169 @@
+package com.amigoscode.isolation.demo;
+
+import java.sql.Connection;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.time.LocalTime;
+import java.time.format.DateTimeFormatter;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Shows what the database sees right now: every account row with the transaction that wrote it,
+ * every session that is inside a transaction, whether it holds a snapshot, and the predicate locks
+ * of SERIALIZABLE sessions. Run it with ./inspect (or .\inspect on Windows) in a second terminal
+ * while ./demo --pause is running.
+ */
+public final class Inspect {
+
+ private static final String ACCOUNTS = """
+ select id, name, balance, xmin, xmax
+ from account
+ order by id
+ """;
+
+ /**
+ * Postgres has no column that shows another session's isolation level. The demo's sessions put
+ * their own level into their application_name, which is the "session" column here.
+ * snapshot_xmin is filled in while a session holds a snapshot.
+ */
+ private static final String SESSIONS = """
+ select a.pid,
+ a.application_name as session,
+ a.state,
+ coalesce(a.backend_xmin::text, '') as snapshot_xmin,
+ coalesce(a.backend_xid::text, '') as own_xid,
+ case when cardinality(pg_blocking_pids(a.pid)) = 0 then ''
+ else array_to_string(pg_blocking_pids(a.pid), ', ') end as waits_for_pid,
+ coalesce(round(extract(epoch from (now() - a.xact_start)) * 1000)::text, '') as in_transaction_ms,
+ left(regexp_replace(a.query, '\\s+', ' ', 'g'), 44) as last_statement
+ from pg_stat_activity a
+ where a.datname = current_database()
+ and a.pid <> pg_backend_pid()
+ and a.backend_type = 'client backend'
+ and a.state <> 'idle'
+ order by a.xact_start nulls last, a.pid
+ """;
+
+ private static final String PREDICATE_LOCKS = """
+ select l.pid,
+ a.application_name as session,
+ coalesce(c.relname::text, '') as relation,
+ l.locktype as covers,
+ coalesce(l.page::text, '') as page,
+ coalesce(l.tuple::text, '') as row_on_page
+ from pg_locks l
+ join pg_stat_activity a on a.pid = l.pid
+ left join pg_class c on c.oid = l.relation
+ where l.mode = 'SIReadLock'
+ order by l.pid, c.relname, l.page nulls first, l.tuple nulls first
+ """;
+
+ public static void main(String[] args) throws Exception {
+ boolean watch = false;
+ for (String arg : args) {
+ if (arg.equals("--watch")) {
+ watch = true;
+ } else {
+ System.out.println("Usage: ./inspect [--watch] (Windows: .\\inspect [--watch])");
+ System.out.println();
+ System.out.println(" --watch refresh every second for one minute (Ctrl+C to stop)");
+ return;
+ }
+ }
+ if (!Db.isUp()) {
+ return;
+ }
+ try (Connection connection = Db.connect()) {
+ int rounds = watch ? 60 : 1;
+ for (int round = 0; round < rounds; round++) {
+ snapshot(connection);
+ if (round < rounds - 1) {
+ Thread.sleep(1000);
+ }
+ }
+ }
+ }
+
+ private static void snapshot(Connection connection) throws SQLException {
+ System.out.println();
+ System.out.println("==== " + LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS")) + " ====");
+ System.out.println();
+ System.out.println("ACCOUNTS (what a NEW transaction would read. xmin = the transaction that wrote this version of");
+ System.out.println(" the row, xmax = a transaction that has locked or replaced it, 0 = none)");
+ if (!tableExists(connection)) {
+ System.out.println(" The account table does not exist yet. Run ./demo once: it creates the table.");
+ return;
+ }
+ printTable(connection, ACCOUNTS);
+ System.out.println();
+ System.out.println("SESSIONS INSIDE A TRANSACTION (snapshot_xmin is filled in while the session holds a snapshot)");
+ int sessions = printTable(connection, SESSIONS);
+ if (sessions == 0) {
+ System.out.println(" none. Nothing is running. Start ./demo --pause in another terminal.");
+ }
+ System.out.println();
+ System.out.println("PREDICATE LOCKS (SIReadLock: what SERIALIZABLE sessions have read. They block nobody)");
+ int locks = printTable(connection, PREDICATE_LOCKS);
+ if (locks == 0) {
+ System.out.println(" none. No SERIALIZABLE transaction is open.");
+ }
+ }
+
+ private static boolean tableExists(Connection connection) throws SQLException {
+ try (Statement statement = connection.createStatement();
+ ResultSet row = statement.executeQuery("select to_regclass('account') is not null")) {
+ row.next();
+ return row.getBoolean(1);
+ }
+ }
+
+ /** Prints a query result as a plain text table and returns the number of rows. */
+ private static int printTable(Connection connection, String sql) throws SQLException {
+ List rows = new ArrayList<>();
+ try (Statement statement = connection.createStatement(); ResultSet result = statement.executeQuery(sql)) {
+ int columns = result.getMetaData().getColumnCount();
+ String[] header = new String[columns];
+ for (int c = 0; c < columns; c++) {
+ header[c] = result.getMetaData().getColumnLabel(c + 1);
+ }
+ rows.add(header);
+ while (result.next()) {
+ String[] row = new String[columns];
+ for (int c = 0; c < columns; c++) {
+ String value = result.getString(c + 1);
+ row[c] = value == null ? "" : value;
+ }
+ rows.add(row);
+ }
+ }
+ if (rows.size() == 1) {
+ return 0;
+ }
+ int[] widths = new int[rows.get(0).length];
+ for (String[] row : rows) {
+ for (int c = 0; c < row.length; c++) {
+ widths[c] = Math.max(widths[c], row[c].length());
+ }
+ }
+ for (int r = 0; r < rows.size(); r++) {
+ StringBuilder line = new StringBuilder(" ");
+ for (int c = 0; c < widths.length; c++) {
+ line.append(String.format("%-" + widths[c] + "s", rows.get(r)[c])).append(" ");
+ }
+ System.out.println(line.toString().stripTrailing());
+ if (r == 0) {
+ StringBuilder rule = new StringBuilder(" ");
+ for (int width : widths) {
+ rule.append("-".repeat(width)).append(" ");
+ }
+ System.out.println(rule.toString().stripTrailing());
+ }
+ }
+ return rows.size() - 1;
+ }
+
+ private Inspect() {
+ }
+}
diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/Lab.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/Lab.java
new file mode 100644
index 0000000..609c57f
--- /dev/null
+++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/Lab.java
@@ -0,0 +1,323 @@
+package com.amigoscode.isolation.demo;
+
+import com.amigoscode.isolation.demo.Outcome.Verdict;
+import com.amigoscode.isolation.demo.Session.Pending;
+import com.amigoscode.isolation.demo.Session.Result;
+import java.io.PrintStream;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.List;
+import java.util.Properties;
+
+/**
+ * Plain SQL in two sessions, one statement at a time, in a fixed order. No Spring, no Hibernate:
+ * this is what Postgres itself does at each isolation level. The demo prints it, and the tests
+ * assert on the {@link Outcome}, so everything the demo shows is also checked.
+ */
+public final class Lab {
+
+ /**
+ * @param forUpdate write-skew only: the read locks the rows it reads (SELECT ... FOR UPDATE)
+ * @param pauseSeconds hold both transactions open for this long in the middle, for ./inspect
+ */
+ public record Options(boolean forUpdate, int pauseSeconds) {
+
+ public static final Options NONE = new Options(false, 0);
+ }
+
+ private static final int WITHDRAWAL = 800;
+
+ private final String url;
+ private final String user;
+ private final String password;
+ private final Timeline timeline;
+
+ /** @param out where to print the timeline, or null to print nothing */
+ public Lab(String url, String user, String password, PrintStream out) {
+ this.url = url;
+ this.user = user;
+ this.password = password;
+ this.timeline = new Timeline(out);
+ }
+
+ public Outcome run(Anomaly anomaly, Level level) {
+ return run(anomaly, level, Options.NONE);
+ }
+
+ public Outcome run(Anomaly anomaly, Level level, Options options) {
+ try (Connection monitor = DriverManager.getConnection(url, user, password)) {
+ Db.reset(monitor);
+ try (Session a = new Session("A", session(), monitor, timeline);
+ Session b = new Session("B", session(), monitor, timeline)) {
+ Run run = new Run(level, options, a, b, monitor);
+ return switch (anomaly) {
+ case DIRTY_READ -> dirtyRead(run);
+ case NON_REPEATABLE_READ -> nonRepeatableRead(run);
+ case PHANTOM -> phantom(run);
+ case LOST_UPDATE -> lostUpdate(run);
+ case WRITE_SKEW -> writeSkew(run);
+ };
+ }
+ } catch (SQLException e) {
+ throw new IllegalStateException(e);
+ }
+ }
+
+ /**
+ * A connection that sends every statement as plain text, the way psql does, instead of as a
+ * prepared statement. Nothing is left open on the server between two statements, so ./inspect
+ * shows exactly which sessions are holding a snapshot.
+ */
+ private Connection session() throws SQLException {
+ Properties properties = new Properties();
+ properties.setProperty("user", user);
+ properties.setProperty("password", password);
+ properties.setProperty("preferQueryMode", "simple");
+ return DriverManager.getConnection(url, properties);
+ }
+
+ /** B changes a balance and does not commit. Can A see the change? */
+ private Outcome dirtyRead(Run run) {
+ Session a = run.a;
+ Session b = run.b;
+ a.exec(run.begin());
+ a.exec("show transaction_isolation");
+ b.exec("begin");
+ b.exec("update account set balance = 0 where id = 1");
+ run.pause();
+ Result read = a.exec("select balance from account where id = 1");
+ b.exec("rollback");
+ a.end();
+
+ if (read.value().equals("0")) {
+ return run.outcome(Anomaly.DIRTY_READ, Verdict.HAPPENED, List.of(read.value()), run.balance(1),
+ "DIRTY READ. Session A read 0, a value that was never committed.");
+ }
+ return run.outcome(Anomaly.DIRTY_READ, Verdict.PREVENTED, List.of(read.value()), run.balance(1),
+ "NO DIRTY READ. Session A read " + read.value() + " while B's uncommitted 0 was in the table."
+ + (run.level == Level.READ_UNCOMMITTED
+ ? " Postgres accepts READ UNCOMMITTED and runs it as READ COMMITTED." : ""));
+ }
+
+ /** A reads one row twice. B changes it and commits in between. */
+ private Outcome nonRepeatableRead(Run run) {
+ Session a = run.a;
+ Session b = run.b;
+ a.exec(run.begin());
+ Result first = a.exec("select balance from account where id = 1");
+ b.exec("begin");
+ b.exec("update account set balance = balance + 100 where id = 1");
+ b.exec("commit");
+ run.pause();
+ Result second = a.exec("select balance from account where id = 1");
+ a.end();
+
+ List seen = List.of(first.value(), second.value());
+ if (!first.value().equals(second.value())) {
+ return run.outcome(Anomaly.NON_REPEATABLE_READ, Verdict.HAPPENED, seen, run.balance(1),
+ "NON-REPEATABLE READ. Session A read the same row twice in one transaction and got "
+ + first.value() + ", then " + second.value() + ".");
+ }
+ return run.outcome(Anomaly.NON_REPEATABLE_READ, Verdict.PREVENTED, seen, run.balance(1),
+ "OK. Session A read " + first.value() + " both times. The committed value is " + run.balance(1)
+ + ", and A will see it in its next transaction.");
+ }
+
+ /** A runs the same query twice. B inserts a row that matches it and commits in between. */
+ private Outcome phantom(Run run) {
+ Session a = run.a;
+ Session b = run.b;
+ String count = "select count(*) from account where owner = 'alice'";
+ a.exec(run.begin());
+ Result first = a.exec(count);
+ b.exec("begin");
+ b.exec("insert into account (id, owner, name, balance) values (3, 'alice', 'holiday', 250)");
+ b.exec("commit");
+ run.pause();
+ Result second = a.exec(count);
+ a.end();
+
+ List seen = List.of(first.value(), second.value());
+ long rows = run.number(count);
+ if (!first.value().equals(second.value())) {
+ return run.outcome(Anomaly.PHANTOM, Verdict.HAPPENED, seen, rows,
+ "PHANTOM READ. The same query returned " + first.value() + " rows, then " + second.value()
+ + ": a row appeared in the middle of Session A's transaction.");
+ }
+ return run.outcome(Anomaly.PHANTOM, Verdict.PREVENTED, seen, rows,
+ "OK. Session A counted " + first.value() + " rows both times. The table has " + rows
+ + ", and A will see the new one in its next transaction.");
+ }
+
+ /** A and B each withdraw 100 from the same account: read the balance, subtract in the application, write. */
+ private Outcome lostUpdate(Run run) {
+ Session a = run.a;
+ Session b = run.b;
+ String read = "select balance from account where id = 1";
+ a.exec(run.begin());
+ long balanceA = a.exec(read).number();
+ b.exec(run.begin());
+ long balanceB = b.exec(read).number();
+ b.comment(balanceB + " - 100 = " + (balanceB - 100) + ", worked out in the application");
+ b.exec("update account set balance = " + (balanceB - 100) + " where id = 1");
+ b.exec("commit");
+ run.pause();
+ a.comment(balanceA + " - 100 = " + (balanceA - 100) + ", worked out in the application");
+ Result write = a.exec("update account set balance = " + (balanceA - 100) + " where id = 1");
+ a.end();
+
+ List seen = List.of(String.valueOf(balanceA), String.valueOf(balanceB));
+ long balance = run.balance(1);
+ if (write.failed()) {
+ return run.failure(Anomaly.LOST_UPDATE, "A", write, seen, balance,
+ "Nothing was lost: the balance is " + balance + " after one withdrawal. "
+ + "A has to run again in a new transaction.");
+ }
+ return run.outcome(Anomaly.LOST_UPDATE, Verdict.HAPPENED, seen, balance,
+ "LOST UPDATE. Two withdrawals of 100 were paid out, but the balance only went from 500 to "
+ + balance + ".");
+ }
+
+ /**
+ * A withdraws 800 from account 1, B withdraws 800 from account 2. Each checks that the two
+ * accounts together hold at least 800. They write different rows.
+ */
+ private Outcome writeSkew(Run run) {
+ Session a = run.a;
+ Session b = run.b;
+ String read = run.options.forUpdate()
+ ? "select balance from account where owner = 'alice' order by id for update"
+ : "select balance from account where owner = 'alice' order by id";
+
+ a.exec(run.begin());
+ Result readA = a.exec(read);
+ boolean allowedA = run.check(a, readA);
+ b.exec(run.begin());
+ Pending readB = b.send(read);
+ run.waited = readB.waited();
+ boolean allowedB = !readB.waited() && run.check(b, readB.result());
+
+ Result failure = null;
+ String failed = null;
+ if (allowedA) {
+ Result write = a.exec("update account set balance = balance - " + WITHDRAWAL + " where id = 1");
+ if (write.failed()) {
+ failure = write;
+ failed = "A";
+ }
+ }
+ if (allowedB) {
+ Result write = b.exec("update account set balance = balance - " + WITHDRAWAL + " where id = 2");
+ if (write.failed()) {
+ failure = write;
+ failed = "B";
+ }
+ }
+ run.pause();
+ Result commitA = a.end();
+ if (commitA.failed()) {
+ failure = commitA;
+ failed = "A";
+ }
+ if (readB.waited()) {
+ allowedB = run.check(b, readB.result());
+ if (allowedB) {
+ b.exec("update account set balance = balance - " + WITHDRAWAL + " where id = 2");
+ }
+ }
+ Result commitB = allowedB || b.failed() ? b.end() : b.exec("rollback");
+ if (commitB.failed()) {
+ failure = commitB;
+ failed = "B";
+ }
+
+ List seen = List.of(String.valueOf(readA.sum()), String.valueOf(readB.result().sum()));
+ long combined = run.number("select sum(balance) from account where owner = 'alice'");
+ if (failure != null) {
+ return run.failure(Anomaly.WRITE_SKEW, failed, failure, seen, combined,
+ "The rule holds: the accounts hold " + combined + " together after one withdrawal. "
+ + failed + " has to run again in a new transaction, and will then see " + combined + ".");
+ }
+ if (combined < 0) {
+ return run.outcome(Anomaly.WRITE_SKEW, Verdict.HAPPENED, seen, combined,
+ "WRITE SKEW. Both sessions saw 1000, both withdrew " + WITHDRAWAL + ", both committed. "
+ + "The accounts now hold " + combined + " together. Neither session changed a row the other one changed.");
+ }
+ return run.outcome(Anomaly.WRITE_SKEW, Verdict.PREVENTED, seen, combined,
+ "OK. Session B had to wait for A's row locks, then read " + readB.result().sum()
+ + " and refused its withdrawal. The accounts hold " + combined + " together.");
+ }
+
+ /** Everything one run needs. */
+ private final class Run {
+
+ private final Level level;
+ private final Options options;
+ private final Session a;
+ private final Session b;
+ private final Connection monitor;
+ private boolean waited;
+
+ private Run(Level level, Options options, Session a, Session b, Connection monitor) {
+ this.level = level;
+ this.options = options;
+ this.a = a;
+ this.b = b;
+ this.monitor = monitor;
+ }
+
+ String begin() {
+ return "begin isolation level " + level.sql();
+ }
+
+ /** The application's rule, applied to what a session read: do the accounts together cover the withdrawal? */
+ boolean check(Session session, Result read) {
+ boolean allowed = read.sum() >= WITHDRAWAL;
+ session.comment(read.addition() + " = " + read.sum() + (allowed
+ ? ", enough for " + WITHDRAWAL + ": go ahead"
+ : ", not enough for " + WITHDRAWAL + ": refuse"));
+ return allowed;
+ }
+
+ void pause() {
+ if (options.pauseSeconds() > 0) {
+ timeline.note("Paused for " + options.pauseSeconds()
+ + " seconds. Run ./inspect in another terminal now.");
+ try {
+ Thread.sleep(options.pauseSeconds() * 1000L);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ }
+ }
+
+ long balance(long accountId) {
+ return number("select balance from account where id = " + accountId);
+ }
+
+ long number(String sql) {
+ try (Statement statement = monitor.createStatement(); ResultSet row = statement.executeQuery(sql)) {
+ row.next();
+ return row.getLong(1);
+ } catch (SQLException e) {
+ throw new IllegalStateException(e);
+ }
+ }
+
+ Outcome outcome(Anomaly anomaly, Verdict verdict, List seen, long finalValue, String result) {
+ return new Outcome(anomaly, level, verdict, seen, null, null, null, waited, finalValue, result);
+ }
+
+ Outcome failure(Anomaly anomaly, String session, Result failure, List seen, long finalValue,
+ String whatNow) {
+ String message = failure.error().lines().findFirst().orElse("").replaceFirst("^ERROR: ", "");
+ Verdict verdict = "40001".equals(failure.sqlState()) ? Verdict.SERIALIZATION_FAILURE : Verdict.PREVENTED;
+ return new Outcome(anomaly, level, verdict, seen, session, failure.sqlState(), message, waited, finalValue,
+ "SERIALIZATION FAILURE (SQLSTATE " + failure.sqlState() + "). Postgres cancelled session "
+ + session + ": \"" + message + "\". " + whatNow);
+ }
+ }
+}
diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/Level.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/Level.java
new file mode 100644
index 0000000..b9a5962
--- /dev/null
+++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/Level.java
@@ -0,0 +1,29 @@
+package com.amigoscode.isolation.demo;
+
+import java.util.Arrays;
+import java.util.Locale;
+import java.util.stream.Collectors;
+
+/** The four isolation levels of the SQL standard, weakest first. */
+public enum Level {
+ READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE;
+
+ /** As written in SQL: "repeatable read". */
+ public String sql() {
+ return name().toLowerCase(Locale.ROOT).replace('_', ' ');
+ }
+
+ /** As written on the command line: "repeatable-read". */
+ public String flag() {
+ return name().toLowerCase(Locale.ROOT).replace('_', '-');
+ }
+
+ static Level from(String value) {
+ return Arrays.stream(values()).filter(level -> level.flag().equals(value)).findFirst()
+ .orElseThrow(() -> new IllegalArgumentException("Unknown level: " + value + ". Use one of: " + names()));
+ }
+
+ static String names() {
+ return Arrays.stream(values()).map(Level::flag).collect(Collectors.joining(" | "));
+ }
+}
diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/Outcome.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/Outcome.java
new file mode 100644
index 0000000..eca7d12
--- /dev/null
+++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/Outcome.java
@@ -0,0 +1,27 @@
+package com.amigoscode.isolation.demo;
+
+import java.util.List;
+
+/**
+ * What one run of one anomaly at one isolation level did.
+ *
+ * @param seen the values the sessions read, in the order they read them
+ * @param failedSession "A" or "B" when the database cancelled one of them, otherwise null
+ * @param sqlState the SQLSTATE of that failure (40001 is a serialization failure), otherwise null
+ * @param error the database's error message, otherwise null
+ * @param waited true when a session had to wait for a lock held by the other one
+ * @param finalValue what is committed at the end: a balance, a row count or a combined balance
+ * @param result the RESULT line
+ */
+public record Outcome(Anomaly anomaly, Level level, Verdict verdict, List seen, String failedSession,
+ String sqlState, String error, boolean waited, long finalValue, String result) {
+
+ public enum Verdict {
+ /** The anomaly happened and nobody was told. */
+ HAPPENED,
+ /** It did not happen and both sessions finished normally. */
+ PREVENTED,
+ /** It did not happen because the database cancelled one transaction with SQLSTATE 40001. */
+ SERIALIZATION_FAILURE
+ }
+}
diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/Session.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/Session.java
new file mode 100644
index 0000000..d477553
--- /dev/null
+++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/Session.java
@@ -0,0 +1,243 @@
+package com.amigoscode.isolation.demo;
+
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Locale;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.stream.Collectors;
+
+/**
+ * One database session (one connection) that is driven one statement at a time. Each statement is
+ * sent as plain SQL, including "begin" and "commit", so the timeline shows exactly what Postgres
+ * received.
+ */
+final class Session implements AutoCloseable {
+
+ /** What one statement returned: rows, a row count, or an error. */
+ record Result(List> rows, int rowCount, String sqlState, String error) {
+
+ boolean failed() {
+ return sqlState != null;
+ }
+
+ /** The first column of the first row. */
+ String value() {
+ return rows.get(0).get(0);
+ }
+
+ long number() {
+ return Long.parseLong(value());
+ }
+
+ /** The first column of every row, added up. */
+ long sum() {
+ return rows.stream().mapToLong(row -> Long.parseLong(row.get(0))).sum();
+ }
+
+ /** The first column of every row: "500 + 500". */
+ String addition() {
+ return rows.stream().map(row -> row.get(0)).collect(Collectors.joining(" + "));
+ }
+ }
+
+ /** A statement that has been sent. It may still be waiting for a lock. */
+ final class Pending {
+
+ private final String sql;
+ private final Future future;
+ private final boolean waited;
+ private Result result;
+
+ private Pending(String sql, Future future, boolean waited) {
+ this.sql = sql;
+ this.future = future;
+ this.waited = waited;
+ }
+
+ /** True when the statement did not return at once because another session holds a lock it needs. */
+ boolean waited() {
+ return waited;
+ }
+
+ /** Waits for the statement to finish, prints what came back, and returns it. */
+ Result result() {
+ if (result == null) {
+ try {
+ result = future.get();
+ } catch (InterruptedException | ExecutionException e) {
+ throw new IllegalStateException(e);
+ }
+ report(sql, result, waited);
+ }
+ return result;
+ }
+ }
+
+ private final String name;
+ private final Connection connection;
+ private final Connection monitor;
+ private final Timeline timeline;
+ private final int pid;
+ private final ExecutorService thread;
+ private boolean failed;
+
+ Session(String name, Connection connection, Connection monitor, Timeline timeline) throws SQLException {
+ this.name = name;
+ this.connection = connection;
+ this.monitor = monitor;
+ this.timeline = timeline;
+ this.thread = Executors.newSingleThreadExecutor(task -> {
+ Thread thread = new Thread(task, "session-" + name);
+ thread.setDaemon(true);
+ return thread;
+ });
+ try (Statement statement = connection.createStatement()) {
+ // The name ./inspect shows for this session.
+ statement.execute("set application_name = 'demo " + name + "'");
+ try (ResultSet row = statement.executeQuery("select pg_backend_pid()")) {
+ row.next();
+ this.pid = row.getInt(1);
+ }
+ }
+ }
+
+ /** Sends one statement and waits for it to finish. */
+ Result exec(String sql) {
+ return send(sql).result();
+ }
+
+ /**
+ * Sends one statement and returns as soon as it has finished or Postgres reports that it is
+ * waiting for a lock. Nothing here guesses with a timer: it asks pg_blocking_pids().
+ */
+ Pending send(String sql) {
+ timeline.step(name, sql);
+ Future future = thread.submit(() -> run(sql));
+ boolean waiting = false;
+ try {
+ while (!future.isDone() && !(waiting = isWaitingForALock())) {
+ Thread.sleep(20);
+ }
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new IllegalStateException(e);
+ }
+ Pending pending = new Pending(sql, future, waiting);
+ if (waiting) {
+ timeline.result(name, "WAITING. Another session holds a lock this statement needs");
+ } else {
+ pending.result();
+ }
+ return pending;
+ }
+
+ /** Ends the transaction: commit, or rollback when a statement in it has already failed. */
+ Result end() {
+ if (failed) {
+ Result result = exec("rollback");
+ timeline.comment(name, "this transaction was cancelled, so there is nothing to commit");
+ return result;
+ }
+ return exec("commit");
+ }
+
+ /** Prints what the application does with a value it read, outside the database. */
+ void comment(String text) {
+ timeline.comment(name, text);
+ }
+
+ /** True when the database has cancelled this session's transaction. */
+ boolean failed() {
+ return failed;
+ }
+
+ private Result run(String sql) {
+ try (Statement statement = connection.createStatement()) {
+ List> rows = new ArrayList<>();
+ if (statement.execute(sql)) {
+ try (ResultSet result = statement.getResultSet()) {
+ int columns = result.getMetaData().getColumnCount();
+ while (result.next()) {
+ List row = new ArrayList<>();
+ for (int c = 1; c <= columns; c++) {
+ row.add(String.valueOf(result.getObject(c)));
+ }
+ rows.add(row);
+ }
+ }
+ return new Result(rows, rows.size(), null, null);
+ }
+ Result result = new Result(rows, statement.getUpdateCount(), null, null);
+ if (sql.strip().toLowerCase(Locale.ROOT).startsWith("begin")) {
+ reportIsolationLevel(statement);
+ }
+ return result;
+ } catch (SQLException e) {
+ return new Result(List.of(), 0, e.getSQLState(), e.getMessage());
+ }
+ }
+
+ /**
+ * Postgres has no column that shows another session's isolation level, so every demo session
+ * puts its own level into its application_name, where ./inspect can read it. SHOW and SET do
+ * not take a snapshot, so this changes nothing about what the transaction will see.
+ */
+ private void reportIsolationLevel(Statement statement) throws SQLException {
+ String level;
+ try (ResultSet row = statement.executeQuery("show transaction_isolation")) {
+ row.next();
+ level = row.getString(1);
+ }
+ statement.execute("set local application_name = 'demo " + name + " (" + level + ")'");
+ }
+
+ private void report(String sql, Result result, boolean waited) {
+ String prefix = waited ? "(stopped waiting) " : "";
+ String verb = sql.strip().toLowerCase(Locale.ROOT).split("\\s+")[0];
+ if (result.failed()) {
+ // The transaction is now unusable until it is rolled back. A failed COMMIT has already rolled it back.
+ failed = !verb.equals("commit") && !verb.equals("rollback");
+ List lines = result.error().lines().map(String::strip).filter(line -> !line.isEmpty()).toList();
+ timeline.result(name, prefix + "ERROR, SQLSTATE " + result.sqlState() + ": "
+ + lines.get(0).replaceFirst("^ERROR: ", ""));
+ lines.stream().skip(1).limit(2).forEach(line -> timeline.result(name, line));
+ } else if (!result.rows().isEmpty()) {
+ timeline.result(name, prefix + result.rows().stream()
+ .map(row -> String.join(" ", row)).collect(Collectors.joining(", ")));
+ } else if (verb.equals("update") || verb.equals("insert") || verb.equals("delete")) {
+ timeline.result(name, prefix + result.rowCount() + (result.rowCount() == 1 ? " row" : " rows"));
+ } else if (verb.equals("rollback") || verb.equals("commit")) {
+ failed = false;
+ }
+ }
+
+ private boolean isWaitingForALock() {
+ try (PreparedStatement statement = monitor.prepareStatement("select cardinality(pg_blocking_pids(?)) > 0")) {
+ statement.setInt(1, pid);
+ try (ResultSet row = statement.executeQuery()) {
+ row.next();
+ return row.getBoolean(1);
+ }
+ } catch (SQLException e) {
+ throw new IllegalStateException(e);
+ }
+ }
+
+ @Override
+ public void close() {
+ thread.shutdownNow();
+ try {
+ connection.close();
+ } catch (SQLException ignored) {
+ // closing anyway
+ }
+ }
+}
diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/Timeline.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/Timeline.java
new file mode 100644
index 0000000..b1a5eea
--- /dev/null
+++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/demo/Timeline.java
@@ -0,0 +1,45 @@
+package com.amigoscode.isolation.demo;
+
+import java.io.PrintStream;
+
+/** Prints what each session does, one step per line. Session B is indented so the two are easy to tell apart. */
+final class Timeline {
+
+ private final PrintStream out;
+
+ /** @param out where to print, or null to print nothing (the tests) */
+ Timeline(PrintStream out) {
+ this.out = out;
+ }
+
+ /** Something a session does. */
+ void step(String session, String text) {
+ print(indent(session) + session + " | " + text);
+ }
+
+ /** What came back. */
+ void result(String session, String text) {
+ print(indent(session) + session + " | -> " + text);
+ }
+
+ /** What the application does with a value, outside the database. */
+ void comment(String session, String text) {
+ print(indent(session) + session + " | # " + text);
+ }
+
+ void note(String text) {
+ print("");
+ print(" " + text);
+ print("");
+ }
+
+ void print(String line) {
+ if (out != null) {
+ out.println(line);
+ }
+ }
+
+ private static String indent(String session) {
+ return session.equals("A") ? " " : " ";
+ }
+}
diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/statement/Statement.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/statement/Statement.java
new file mode 100644
index 0000000..f241f7f
--- /dev/null
+++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/statement/Statement.java
@@ -0,0 +1,19 @@
+package com.amigoscode.isolation.statement;
+
+import java.util.List;
+
+/** What the customer is shown: one line per account, then how many accounts and the total. */
+public record Statement(String owner, List lines, long accountCount, long total) {
+
+ public record Line(String account, long balance) {
+ }
+
+ public long sumOfLines() {
+ return lines.stream().mapToLong(Line::balance).sum();
+ }
+
+ /** A statement a customer can trust: the lines are all the accounts, and they add up to the total. */
+ public boolean addsUp() {
+ return lines.size() == accountCount && sumOfLines() == total;
+ }
+}
diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/statement/StatementService.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/statement/StatementService.java
new file mode 100644
index 0000000..3c900da
--- /dev/null
+++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/statement/StatementService.java
@@ -0,0 +1,37 @@
+package com.amigoscode.isolation.statement;
+
+import com.amigoscode.isolation.account.AccountRepository;
+import com.amigoscode.isolation.checkpoint.Checkpoint;
+import com.amigoscode.isolation.statement.Statement.Line;
+import java.util.List;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Isolation;
+import org.springframework.transaction.annotation.Transactional;
+
+@Service
+public class StatementService {
+
+ private final AccountRepository accounts;
+ private final Checkpoint checkpoint;
+
+ public StatementService(AccountRepository accounts, Checkpoint checkpoint) {
+ this.accounts = accounts;
+ this.checkpoint = checkpoint;
+ }
+
+ /**
+ * Three queries, one transaction. At REPEATABLE READ the transaction takes one snapshot at its
+ * first query and every later query reads from that same snapshot, so the lines, the count and
+ * the total always describe the same moment, whatever other sessions commit in between.
+ */
+ @Transactional(readOnly = true, isolation = Isolation.REPEATABLE_READ)
+ public Statement statement(String owner) {
+ List lines = accounts.findByOwnerOrderById(owner).stream() // QUERY 1: the lines
+ .map(account -> new Line(account.getName(), account.getBalance()))
+ .toList();
+ checkpoint.reached(Checkpoint.LINES_READ); // ...time passes...
+ long accountCount = accounts.countByOwner(owner); // QUERY 2: how many accounts
+ long total = accounts.totalBalance(owner); // QUERY 3: the total
+ return new Statement(owner, lines, accountCount, total);
+ }
+}
diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/withdrawal/InsufficientFundsException.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/withdrawal/InsufficientFundsException.java
new file mode 100644
index 0000000..0a6a478
--- /dev/null
+++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/withdrawal/InsufficientFundsException.java
@@ -0,0 +1,9 @@
+package com.amigoscode.isolation.withdrawal;
+
+public class InsufficientFundsException extends RuntimeException {
+
+ public InsufficientFundsException(long accountId, long amount, long available) {
+ super("Cannot withdraw " + amount + " from account " + accountId
+ + ": the customer's accounts hold " + available + " in total");
+ }
+}
diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/withdrawal/WithdrawalConflictException.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/withdrawal/WithdrawalConflictException.java
new file mode 100644
index 0000000..7216916
--- /dev/null
+++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/withdrawal/WithdrawalConflictException.java
@@ -0,0 +1,10 @@
+package com.amigoscode.isolation.withdrawal;
+
+/** Every attempt was cancelled by the database. Nothing was withdrawn, and it is safe to try again. */
+public class WithdrawalConflictException extends RuntimeException {
+
+ public WithdrawalConflictException(long accountId, int attempts, Throwable cause) {
+ super("Withdrawal from account " + accountId + " was cancelled " + attempts
+ + " times by concurrent transactions. Nothing was withdrawn. Try again.", cause);
+ }
+}
diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/withdrawal/WithdrawalService.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/withdrawal/WithdrawalService.java
new file mode 100644
index 0000000..7f43b9d
--- /dev/null
+++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/withdrawal/WithdrawalService.java
@@ -0,0 +1,35 @@
+package com.amigoscode.isolation.withdrawal;
+
+import org.springframework.dao.ConcurrencyFailureException;
+import org.springframework.stereotype.Service;
+
+/**
+ * Deliberately NOT transactional. When Postgres cancels a transaction with SQLSTATE 40001 the whole
+ * transaction is gone, so the only way to try again is a brand new transaction that reads
+ * everything again. The loop therefore lives outside the transactional bean.
+ */
+@Service
+public class WithdrawalService {
+
+ public static final int MAX_ATTEMPTS = 3;
+
+ private final Withdrawer withdrawer;
+
+ public WithdrawalService(Withdrawer withdrawer) {
+ this.withdrawer = withdrawer;
+ }
+
+ public long withdraw(long accountId, long amount) {
+ for (int attempt = 1; ; attempt++) {
+ try {
+ return withdrawer.withdraw(accountId, amount);
+ } catch (ConcurrencyFailureException e) {
+ // SQLSTATE 40001 arrives as CannotAcquireLockException, a ConcurrencyFailureException.
+ // The transaction is already rolled back, so the next attempt re-reads the balances.
+ if (attempt == MAX_ATTEMPTS) {
+ throw new WithdrawalConflictException(accountId, attempt, e);
+ }
+ }
+ }
+ }
+}
diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/withdrawal/Withdrawer.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/withdrawal/Withdrawer.java
new file mode 100644
index 0000000..19aae44
--- /dev/null
+++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/java/com/amigoscode/isolation/withdrawal/Withdrawer.java
@@ -0,0 +1,47 @@
+package com.amigoscode.isolation.withdrawal;
+
+import com.amigoscode.isolation.account.Account;
+import com.amigoscode.isolation.account.AccountNotFoundException;
+import com.amigoscode.isolation.account.AccountRepository;
+import com.amigoscode.isolation.checkpoint.Checkpoint;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Isolation;
+import org.springframework.transaction.annotation.Transactional;
+
+/** One database transaction per call: one attempt at a withdrawal. */
+@Service
+public class Withdrawer {
+
+ private final AccountRepository accounts;
+ private final Checkpoint checkpoint;
+
+ public Withdrawer(AccountRepository accounts, Checkpoint checkpoint) {
+ this.accounts = accounts;
+ this.checkpoint = checkpoint;
+ }
+
+ /**
+ * The rule: one account may go below zero, as long as all of the customer's accounts together
+ * stay at zero or above. So the decision is based on rows this transaction READS but does not
+ * WRITE. Only SERIALIZABLE makes the database track that: if another transaction changed what
+ * this one read, one of the two is cancelled with SQLSTATE 40001, and WithdrawalService runs it
+ * again.
+ *
+ * @return the new balance of the account
+ */
+ @Transactional(isolation = Isolation.SERIALIZABLE)
+ public long withdraw(long accountId, long amount) {
+ if (amount <= 0) {
+ throw new IllegalArgumentException("amount must be positive, got " + amount);
+ }
+ Account account = accounts.findById(accountId) // READ this account
+ .orElseThrow(() -> new AccountNotFoundException(accountId));
+ long available = accounts.totalBalance(account.getOwner()); // READ all the customer's accounts
+ if (available < amount) { // CHECK the rule
+ throw new InsufficientFundsException(accountId, amount, available);
+ }
+ checkpoint.reached(Checkpoint.FUNDS_CHECKED); // ...time passes...
+ account.setBalance(account.getBalance() - amount); // WRITE a value computed from the READ
+ return account.getBalance();
+ }
+}
diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/main/resources/application.properties b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/resources/application.properties
new file mode 100644
index 0000000..6de13d3
--- /dev/null
+++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/resources/application.properties
@@ -0,0 +1,16 @@
+spring.application.name=isolation-levels
+
+# Postgres from compose.yaml. Port 5448 so it does not clash with a Postgres you already run.
+spring.datasource.url=${DB_URL:jdbc:postgresql://localhost:5448/bank}
+spring.datasource.username=${DB_USER:bank}
+spring.datasource.password=${DB_PASSWORD:bank}
+# The name ./inspect shows for the application's database sessions.
+spring.datasource.hikari.data-source-properties.ApplicationName=bank-app
+
+spring.jpa.hibernate.ddl-auto=none
+spring.jpa.open-in-view=false
+spring.sql.init.mode=always
+spring.main.web-application-type=none
+
+# Uncomment to see every SQL statement Hibernate sends.
+# logging.level.org.hibernate.SQL=DEBUG
diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/main/resources/schema.sql b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/resources/schema.sql
new file mode 100644
index 0000000..fd5a4da
--- /dev/null
+++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/main/resources/schema.sql
@@ -0,0 +1,13 @@
+create table if not exists account (
+ id bigint primary key,
+ owner text not null,
+ name text not null,
+ balance bigint not null
+);
+
+-- One customer, two accounts. The bank's rule: a single account may go below zero,
+-- as long as the customer's accounts added together stay at zero or above.
+insert into account (id, owner, name, balance)
+values (1, 'alice', 'current', 500),
+ (2, 'alice', 'savings', 500)
+on conflict (id) do nothing;
diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/test/java/com/amigoscode/isolation/BaselineIT.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/test/java/com/amigoscode/isolation/BaselineIT.java
new file mode 100644
index 0000000..966aa7e
--- /dev/null
+++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/test/java/com/amigoscode/isolation/BaselineIT.java
@@ -0,0 +1,56 @@
+package com.amigoscode.isolation;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import com.amigoscode.isolation.statement.Statement;
+import com.amigoscode.isolation.support.IntegrationTest;
+import com.amigoscode.isolation.withdrawal.InsufficientFundsException;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+
+/** The bank's rules with one customer at a time. These pass from the start and must stay green. */
+@Tag("baseline")
+class BaselineIT extends IntegrationTest {
+
+ @Test
+ @DisplayName("Withdrawal: 100 from the current account leaves 400, and the new balance is returned")
+ void withdrawalLowersTheBalance() {
+ long newBalance = withdrawalService.withdraw(CURRENT, 100);
+
+ assertThat(newBalance).as("returned balance").isEqualTo(400);
+ assertThat(balance(CURRENT)).as("current account").isEqualTo(400);
+ assertThat(balance(SAVINGS)).as("savings account").isEqualTo(500);
+ }
+
+ @Test
+ @DisplayName("Withdrawal: one account may go below zero while both accounts together stay at zero or above")
+ void oneAccountMayGoNegative() {
+ withdrawalService.withdraw(CURRENT, 800);
+
+ assertThat(balance(CURRENT)).as("current account").isEqualTo(-300);
+ assertThat(combinedBalance()).as("both accounts together").isEqualTo(200);
+ }
+
+ @Test
+ @DisplayName("Withdrawal: refused when both accounts together cannot cover it, and nothing changes")
+ void refusedWhenTheAccountsTogetherCannotCoverIt() {
+ assertThatThrownBy(() -> withdrawalService.withdraw(CURRENT, 1001))
+ .isInstanceOf(InsufficientFundsException.class);
+
+ assertThat(balance(CURRENT)).as("current account").isEqualTo(500);
+ assertThat(combinedBalance()).as("both accounts together").isEqualTo(1000);
+ }
+
+ @Test
+ @DisplayName("Statement: with nobody else writing, it lists both accounts and they add up to the total")
+ void statementAddsUpWhenNobodyElseIsWriting() {
+ Statement statement = statementService.statement("alice");
+
+ assertThat(statement.lines()).as("lines").hasSize(2);
+ assertThat(statement.accountCount()).as("account count").isEqualTo(2);
+ assertThat(statement.total()).as("total").isEqualTo(1000);
+ assertThat(statement.addsUp()).as("lines add up to the total").isTrue();
+ }
+}
diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/test/java/com/amigoscode/isolation/Check.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/test/java/com/amigoscode/isolation/Check.java
new file mode 100644
index 0000000..18aad18
--- /dev/null
+++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/test/java/com/amigoscode/isolation/Check.java
@@ -0,0 +1,114 @@
+package com.amigoscode.isolation;
+
+import static org.junit.platform.engine.discovery.DiscoverySelectors.selectPackage;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+import org.junit.platform.engine.TestExecutionResult;
+import org.junit.platform.engine.discovery.ClassNameFilter;
+import org.junit.platform.launcher.Launcher;
+import org.junit.platform.launcher.LauncherDiscoveryRequest;
+import org.junit.platform.launcher.TagFilter;
+import org.junit.platform.launcher.TestExecutionListener;
+import org.junit.platform.launcher.TestIdentifier;
+import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder;
+import org.junit.platform.launcher.core.LauncherFactory;
+
+/**
+ * Runs the tests that belong to one task and prints one line per acceptance criterion.
+ * ./check 2 checks task 2, ./check checks everything. On Windows: .\check 2
+ * (./mvnw verify runs the same tests the usual Maven way.)
+ */
+public final class Check {
+
+ /** Tasks that have tests. Tasks 3, 5 and 7 are inspection tasks: you answer questions, no code. */
+ private static final Map TASKS = new LinkedHashMap<>();
+
+ static {
+ TASKS.put("baseline", "Baseline: the bank's rules, one customer at a time (passes from the start, must stay green)");
+ TASKS.put("1", "Task 1: See the statement that does not add up");
+ TASKS.put("2", "Task 2: Fix the statement with REPEATABLE READ");
+ TASKS.put("4", "Task 4: Stop the lost update, and retry the serialization failure");
+ TASKS.put("6", "Task 6: Fix the write skew with SERIALIZABLE");
+ TASKS.put("8", "Task 8: Isolation levels vs locking");
+ }
+
+ public static void main(String[] args) {
+ if (args.length > 1 || (args.length == 1 && !args[0].matches("[1-8]"))) {
+ System.out.println("Usage: ./check [task] task is a number from 1 to 8. No number checks everything.");
+ System.exit(2);
+ }
+ if (args.length == 1 && !TASKS.containsKey(args[0])) {
+ System.out.println();
+ System.out.println("Task " + args[0] + " is an inspection task. There is no code to write and no test to pass:");
+ System.out.println("follow its steps in INTERVIEW_TASKS.md and answer the questions.");
+ System.out.println();
+ return;
+ }
+
+ boolean allGreen = true;
+ Launcher launcher = LauncherFactory.create();
+ for (Map.Entry task : TASKS.entrySet()) {
+ if (args.length == 1 && !task.getKey().equals(args[0])) {
+ continue;
+ }
+ String tag = task.getKey().equals("baseline") ? "baseline" : "task" + task.getKey();
+ LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request()
+ .selectors(selectPackage(Check.class.getPackageName()))
+ .filters(ClassNameFilter.includeClassNamePatterns(".*"), TagFilter.includeTags(tag))
+ .build();
+ System.out.println();
+ System.out.println(task.getValue());
+ Results results = new Results();
+ launcher.execute(request, results);
+ System.out.println(" " + results.passed + " of " + results.total + " pass");
+ allGreen &= results.passed == results.total && results.total > 0;
+ }
+ System.out.println();
+ System.exit(allGreen ? 0 : 1);
+ }
+
+ private static final class Results implements TestExecutionListener {
+
+ private int total;
+ private int passed;
+
+ @Override
+ public void executionFinished(TestIdentifier test, TestExecutionResult result) {
+ boolean ok = result.getStatus() == TestExecutionResult.Status.SUCCESSFUL;
+ if (!test.isTest()) {
+ // A container that fails (for example the Spring context cannot start) takes its tests with it.
+ if (!ok) {
+ total++;
+ System.out.println(" [FAIL] " + test.getDisplayName() + " could not start");
+ result.getThrowable().ifPresent(Results::printReason);
+ }
+ return;
+ }
+ total++;
+ if (ok) {
+ passed++;
+ System.out.println(" [PASS] " + test.getDisplayName());
+ } else {
+ System.out.println(" [FAIL] " + test.getDisplayName());
+ result.getThrowable().ifPresent(Results::printReason);
+ }
+ }
+
+ private static void printReason(Throwable throwable) {
+ Throwable root = throwable;
+ while (root.getCause() != null && root.getCause() != root && root.getMessage() == null) {
+ root = root.getCause();
+ }
+ String message = root.getMessage() == null ? root.getClass().getSimpleName() : root.getMessage();
+ message.strip().lines()
+ .map(String::strip)
+ .filter(line -> !line.isEmpty())
+ .limit(6)
+ .forEach(line -> System.out.println(" " + line));
+ }
+ }
+
+ private Check() {
+ }
+}
diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/test/java/com/amigoscode/isolation/IsolationVsLockingIT.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/test/java/com/amigoscode/isolation/IsolationVsLockingIT.java
new file mode 100644
index 0000000..6802c75
--- /dev/null
+++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/test/java/com/amigoscode/isolation/IsolationVsLockingIT.java
@@ -0,0 +1,44 @@
+package com.amigoscode.isolation;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import com.amigoscode.isolation.demo.Anomaly;
+import com.amigoscode.isolation.demo.Lab;
+import com.amigoscode.isolation.demo.Level;
+import com.amigoscode.isolation.demo.Outcome;
+import com.amigoscode.isolation.demo.Outcome.Verdict;
+import com.amigoscode.isolation.support.IntegrationTest;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+
+/**
+ * Task 8. These pass from the start: they pin down the difference between raising the isolation
+ * level and taking a lock, on the same write-skew scenario.
+ */
+@Tag("task8")
+class IsolationVsLockingIT extends IntegrationTest {
+
+ @Test
+ @DisplayName("A lock makes the other session WAIT: with SELECT ... FOR UPDATE at READ COMMITTED, B waits for A, then reads 200 and refuses")
+ void forUpdateMakesTheSecondSessionWait() {
+ Outcome outcome = lab().run(Anomaly.WRITE_SKEW, Level.READ_COMMITTED, new Lab.Options(true, 0));
+
+ assertThat(outcome.waited()).as("session B had to wait for a lock").isTrue();
+ assertThat(outcome.seen()).as("the combined balance each session saw").containsExactly("1000", "200");
+ assertThat(outcome.failedSession()).as("session cancelled by the database").isNull();
+ assertThat(outcome.finalValue()).as("both accounts together").isEqualTo(200);
+ assertThat(outcome.verdict()).isEqualTo(Verdict.PREVENTED);
+ }
+
+ @Test
+ @DisplayName("An isolation level makes nobody wait: at SERIALIZABLE both sessions read 1000 at once, and one is CANCELLED instead")
+ void serializableCancelsInsteadOfWaiting() {
+ Outcome outcome = lab().run(Anomaly.WRITE_SKEW, Level.SERIALIZABLE);
+
+ assertThat(outcome.waited()).as("a session had to wait for a lock").isFalse();
+ assertThat(outcome.seen()).as("the combined balance each session saw").containsExactly("1000", "1000");
+ assertThat(outcome.failedSession()).as("session cancelled by the database").isEqualTo("B");
+ assertThat(outcome.finalValue()).as("both accounts together").isEqualTo(200);
+ }
+}
diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/test/java/com/amigoscode/isolation/LostUpdateIT.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/test/java/com/amigoscode/isolation/LostUpdateIT.java
new file mode 100644
index 0000000..81471a0
--- /dev/null
+++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/test/java/com/amigoscode/isolation/LostUpdateIT.java
@@ -0,0 +1,80 @@
+package com.amigoscode.isolation;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.catchThrowable;
+
+import com.amigoscode.isolation.checkpoint.Checkpoint;
+import com.amigoscode.isolation.demo.Anomaly;
+import com.amigoscode.isolation.demo.Level;
+import com.amigoscode.isolation.demo.Outcome;
+import com.amigoscode.isolation.demo.Outcome.Verdict;
+import com.amigoscode.isolation.support.IntegrationTest;
+import java.sql.SQLException;
+import java.util.concurrent.atomic.AtomicReference;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+import org.springframework.dao.CannotAcquireLockException;
+
+@Tag("task4")
+class LostUpdateIT extends IntegrationTest {
+
+ @Test
+ @DisplayName("READ COMMITTED: lost update. Two withdrawals of 100 are paid out and the balance only goes from 500 to 400")
+ void readCommittedLosesAnUpdate() {
+ Outcome outcome = lab().run(Anomaly.LOST_UPDATE, Level.READ_COMMITTED);
+
+ assertThat(outcome.seen()).as("the balance each session read").containsExactly("500", "500");
+ assertThat(outcome.finalValue()).as("balance after two withdrawals of 100").isEqualTo(400);
+ assertThat(outcome.verdict()).isEqualTo(Verdict.HAPPENED);
+ }
+
+ @Test
+ @DisplayName("REPEATABLE READ: the second writer is cancelled with SQLSTATE 40001, could not serialize access due to concurrent update")
+ void repeatableReadCancelsTheSecondWriter() {
+ Outcome outcome = lab().run(Anomaly.LOST_UPDATE, Level.REPEATABLE_READ);
+
+ assertThat(outcome.verdict()).isEqualTo(Verdict.SERIALIZATION_FAILURE);
+ assertThat(outcome.sqlState()).as("SQLSTATE").isEqualTo("40001");
+ assertThat(outcome.error()).isEqualTo("could not serialize access due to concurrent update");
+ assertThat(outcome.finalValue()).as("balance after the one withdrawal that committed").isEqualTo(400);
+ }
+
+ @Test
+ @DisplayName("Withdrawer: one attempt that loses the race fails with Spring's CannotAcquireLockException, caused by SQLSTATE 40001")
+ void theLosingAttemptFailsWithCannotAcquireLockException() {
+ // In the middle of our attempt, another customer session withdraws 100 from the same account and commits.
+ checkpoint.onFirst(Checkpoint.FUNDS_CHECKED, () -> inAnotherThread(() -> withdrawer.withdraw(CURRENT, 100)));
+
+ Throwable thrown = catchThrowable(() -> withdrawer.withdraw(CURRENT, 100));
+
+ assertThat(thrown).as("what one losing attempt throws").isInstanceOf(CannotAcquireLockException.class);
+ assertThat(thrown).rootCause().isInstanceOf(SQLException.class);
+ assertThat(((SQLException) rootCause(thrown)).getSQLState()).as("SQLSTATE").isEqualTo("40001");
+ assertThat(balance(CURRENT)).as("balance: only the other withdrawal committed").isEqualTo(400);
+ }
+
+ @Test
+ @DisplayName("Withdrawal: two withdrawals of 100 from the same account both go through, one on its second attempt, and the balance is 300")
+ void bothWithdrawalsGoThroughAndNothingIsLost() {
+ AtomicReference other = new AtomicReference<>();
+ checkpoint.onFirst(Checkpoint.FUNDS_CHECKED,
+ () -> other.set(inAnotherThread(() -> withdrawalService.withdraw(CURRENT, 100))));
+
+ long newBalance = withdrawalService.withdraw(CURRENT, 100);
+
+ assertThat(other.get()).as("what the other withdrawal threw").isNull();
+ assertThat(balance(CURRENT)).as("balance after two withdrawals of 100").isEqualTo(300);
+ assertThat(newBalance).as("balance returned to the customer who retried").isEqualTo(300);
+ assertThat(checkpoint.arrivals(Checkpoint.FUNDS_CHECKED))
+ .as("attempts: ours, the other customer's, and our second one").isEqualTo(3);
+ }
+
+ private static Throwable rootCause(Throwable throwable) {
+ Throwable root = throwable;
+ while (root.getCause() != null) {
+ root = root.getCause();
+ }
+ return root;
+ }
+}
diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/test/java/com/amigoscode/isolation/ReadCommittedIT.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/test/java/com/amigoscode/isolation/ReadCommittedIT.java
new file mode 100644
index 0000000..ac5f00e
--- /dev/null
+++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/test/java/com/amigoscode/isolation/ReadCommittedIT.java
@@ -0,0 +1,77 @@
+package com.amigoscode.isolation;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import com.amigoscode.isolation.demo.Anomaly;
+import com.amigoscode.isolation.demo.Level;
+import com.amigoscode.isolation.demo.Outcome;
+import com.amigoscode.isolation.demo.Outcome.Verdict;
+import com.amigoscode.isolation.support.IntegrationTest;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.transaction.PlatformTransactionManager;
+import org.springframework.transaction.support.TransactionTemplate;
+
+/**
+ * Task 1. These tests pass on purpose: they pin down what Postgres does at its default level, and
+ * at the level below it. Each one drives two sessions with plain SQL, one statement at a time.
+ */
+@Tag("task1")
+class ReadCommittedIT extends IntegrationTest {
+
+ @Autowired
+ private PlatformTransactionManager transactionManager;
+
+ @Test
+ @DisplayName("Default: Postgres runs at READ COMMITTED, and so does a Spring transaction that sets no isolation level")
+ void theDefaultIsReadCommitted() {
+ String postgresDefault = jdbc.queryForObject("show default_transaction_isolation", String.class);
+ String springDefault = new TransactionTemplate(transactionManager)
+ .execute(status -> isolationLevelOfThisTransaction());
+
+ assertThat(postgresDefault).as("default_transaction_isolation").isEqualTo("read committed");
+ assertThat(springDefault).as("level of a default Spring transaction").isEqualTo("read committed");
+ }
+
+ @Test
+ @DisplayName("READ COMMITTED: non-repeatable read. One transaction reads a balance twice and gets 500, then 600")
+ void nonRepeatableRead() {
+ Outcome outcome = lab().run(Anomaly.NON_REPEATABLE_READ, Level.READ_COMMITTED);
+
+ assertThat(outcome.seen()).as("what session A read, in one transaction").containsExactly("500", "600");
+ assertThat(outcome.verdict()).isEqualTo(Verdict.HAPPENED);
+ }
+
+ @Test
+ @DisplayName("READ COMMITTED: phantom read. The same count returns 2 rows, then 3")
+ void phantomRead() {
+ Outcome outcome = lab().run(Anomaly.PHANTOM, Level.READ_COMMITTED);
+
+ assertThat(outcome.seen()).as("what session A counted, in one transaction").containsExactly("2", "3");
+ assertThat(outcome.verdict()).isEqualTo(Verdict.HAPPENED);
+ }
+
+ @Test
+ @DisplayName("READ UNCOMMITTED: no dirty read in Postgres. Another session's uncommitted change stays invisible")
+ void noDirtyReadEvenAtReadUncommitted() {
+ Outcome outcome = lab().run(Anomaly.DIRTY_READ, Level.READ_UNCOMMITTED);
+
+ assertThat(outcome.seen()).as("what session A read while B's uncommitted 0 was in the table")
+ .containsExactly("500");
+ assertThat(outcome.verdict()).isEqualTo(Verdict.PREVENTED);
+ }
+
+ @Test
+ @DisplayName("READ UNCOMMITTED: for every anomaly it behaves exactly like READ COMMITTED")
+ void readUncommittedBehavesAsReadCommitted() {
+ for (Anomaly anomaly : Anomaly.values()) {
+ Outcome readUncommitted = lab().run(anomaly, Level.READ_UNCOMMITTED);
+ Outcome readCommitted = lab().run(anomaly, Level.READ_COMMITTED);
+
+ assertThat(readUncommitted.verdict()).as(anomaly.flag()).isEqualTo(readCommitted.verdict());
+ assertThat(readUncommitted.seen()).as(anomaly.flag()).isEqualTo(readCommitted.seen());
+ }
+ }
+}
diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/test/java/com/amigoscode/isolation/StatementIT.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/test/java/com/amigoscode/isolation/StatementIT.java
new file mode 100644
index 0000000..1b14de8
--- /dev/null
+++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/test/java/com/amigoscode/isolation/StatementIT.java
@@ -0,0 +1,90 @@
+package com.amigoscode.isolation;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import com.amigoscode.isolation.checkpoint.Checkpoint;
+import com.amigoscode.isolation.demo.Anomaly;
+import com.amigoscode.isolation.demo.Level;
+import com.amigoscode.isolation.demo.Outcome;
+import com.amigoscode.isolation.demo.Outcome.Verdict;
+import com.amigoscode.isolation.statement.Statement;
+import com.amigoscode.isolation.support.IntegrationTest;
+import java.util.concurrent.atomic.AtomicReference;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+
+@Tag("task2")
+class StatementIT extends IntegrationTest {
+
+ @Test
+ @DisplayName("REPEATABLE READ: one transaction reads a balance twice and gets 500 both times, although 600 is committed")
+ void repeatableReadReadsTheSameValueTwice() {
+ Outcome outcome = lab().run(Anomaly.NON_REPEATABLE_READ, Level.REPEATABLE_READ);
+
+ assertThat(outcome.seen()).as("what session A read, in one transaction").containsExactly("500", "500");
+ assertThat(outcome.finalValue()).as("committed balance").isEqualTo(600);
+ assertThat(outcome.verdict()).isEqualTo(Verdict.PREVENTED);
+ }
+
+ @Test
+ @DisplayName("REPEATABLE READ: no phantom in Postgres. The same count returns 2 rows both times, although 3 are committed")
+ void repeatableReadHasNoPhantomsInPostgres() {
+ Outcome outcome = lab().run(Anomaly.PHANTOM, Level.REPEATABLE_READ);
+
+ assertThat(outcome.seen()).as("what session A counted, in one transaction").containsExactly("2", "2");
+ assertThat(outcome.finalValue()).as("committed rows").isEqualTo(3);
+ assertThat(outcome.verdict()).isEqualTo(Verdict.PREVENTED);
+ }
+
+ @Test
+ @DisplayName("Statement: a deposit commits between its queries, and the lines still add up to the total")
+ void aDepositInTheMiddleDoesNotBreakTheStatement() {
+ checkpoint.onFirst(Checkpoint.LINES_READ,
+ () -> inAnotherSession("update account set balance = balance + 100 where id = 1"));
+
+ Statement statement = statementService.statement("alice");
+
+ assertThat(balance(CURRENT)).as("the deposit is committed").isEqualTo(600);
+ assertThat(statement.total()).as("total, when the lines add up to " + statement.sumOfLines())
+ .isEqualTo(statement.sumOfLines());
+ }
+
+ @Test
+ @DisplayName("Statement: an account is opened between its queries, and the count still matches the lines")
+ void aNewAccountInTheMiddleDoesNotBreakTheStatement() {
+ checkpoint.onFirst(Checkpoint.LINES_READ, () -> inAnotherSession(
+ "insert into account (id, owner, name, balance) values (3, 'alice', 'holiday', 250)"));
+
+ Statement statement = statementService.statement("alice");
+
+ assertThat(statement.accountCount()).as("account count, when the statement lists "
+ + statement.lines().size() + " lines").isEqualTo(statement.lines().size());
+ assertThat(statement.total()).as("total, when the lines add up to " + statement.sumOfLines())
+ .isEqualTo(statement.sumOfLines());
+ }
+
+ @Test
+ @DisplayName("Statement: all of its queries run in one REPEATABLE READ transaction")
+ void statementRunsAtRepeatableRead() {
+ AtomicReference level = new AtomicReference<>();
+ checkpoint.onFirst(Checkpoint.LINES_READ, () -> level.set(isolationLevelOfThisTransaction()));
+
+ statementService.statement("alice");
+
+ assertThat(level.get()).as("isolation level in the middle of statement()").isEqualTo("repeatable read");
+ }
+
+ @Test
+ @DisplayName("Statement: the snapshot ends with the transaction. The next statement shows the deposit")
+ void theNextStatementSeesTheDeposit() {
+ checkpoint.onFirst(Checkpoint.LINES_READ,
+ () -> inAnotherSession("update account set balance = balance + 100 where id = 1"));
+ statementService.statement("alice");
+
+ Statement next = statementService.statement("alice");
+
+ assertThat(next.total()).as("total of the next statement").isEqualTo(1100);
+ assertThat(next.addsUp()).as("lines add up to the total").isTrue();
+ }
+}
diff --git a/java/concepts/junior-mid/09-isolation-levels/solution/src/test/java/com/amigoscode/isolation/WithdrawalServiceRetryTest.java b/java/concepts/junior-mid/09-isolation-levels/solution/src/test/java/com/amigoscode/isolation/WithdrawalServiceRetryTest.java
new file mode 100644
index 0000000..1337190
--- /dev/null
+++ b/java/concepts/junior-mid/09-isolation-levels/solution/src/test/java/com/amigoscode/isolation/WithdrawalServiceRetryTest.java
@@ -0,0 +1,99 @@
+package com.amigoscode.isolation;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import com.amigoscode.isolation.withdrawal.InsufficientFundsException;
+import com.amigoscode.isolation.withdrawal.WithdrawalConflictException;
+import com.amigoscode.isolation.withdrawal.WithdrawalService;
+import com.amigoscode.isolation.withdrawal.Withdrawer;
+import java.util.ArrayDeque;
+import java.util.Deque;
+import java.util.List;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+import org.springframework.core.annotation.AnnotatedElementUtils;
+import org.springframework.dao.CannotAcquireLockException;
+import org.springframework.transaction.annotation.Transactional;
+
+/**
+ * Unit tests: no Spring, no database. Withdrawer is replaced by a scripted stub, so only the retry
+ * loop in WithdrawalService is under test and the whole class runs in milliseconds.
+ */
+@Tag("task4")
+class WithdrawalServiceRetryTest {
+
+ @Test
+ @DisplayName("Retry: when Postgres cancels the transaction (40001), the withdrawal is tried again and succeeds")
+ void retriesAfterASerializationFailure() {
+ ScriptedWithdrawer withdrawer = new ScriptedWithdrawer(serializationFailure(), 300L);
+
+ long newBalance = new WithdrawalService(withdrawer).withdraw(1, 100);
+
+ assertThat(newBalance).as("returned balance").isEqualTo(300);
+ assertThat(withdrawer.attempts).as("attempts").isEqualTo(2);
+ }
+
+ @Test
+ @DisplayName("Retry: after 3 cancelled attempts it stops and throws WithdrawalConflictException")
+ void givesUpAfterThreeAttempts() {
+ ScriptedWithdrawer withdrawer = new ScriptedWithdrawer(serializationFailure());
+
+ assertThatThrownBy(() -> new WithdrawalService(withdrawer).withdraw(1, 100))
+ .isInstanceOf(WithdrawalConflictException.class);
+
+ assertThat(withdrawer.attempts).as("attempts").isEqualTo(3);
+ }
+
+ @Test
+ @DisplayName("Retry: insufficient funds is not retried, because trying again cannot change the answer")
+ void doesNotRetryInsufficientFunds() {
+ ScriptedWithdrawer withdrawer = new ScriptedWithdrawer(new InsufficientFundsException(1, 100, 0));
+
+ assertThatThrownBy(() -> new WithdrawalService(withdrawer).withdraw(1, 100))
+ .isInstanceOf(InsufficientFundsException.class);
+
+ assertThat(withdrawer.attempts).as("attempts").isEqualTo(1);
+ }
+
+ @Test
+ @DisplayName("Retry: WithdrawalService is not @Transactional, so every attempt gets a new transaction")
+ void theRetryLoopIsOutsideTheTransaction() throws NoSuchMethodException {
+ assertThat(AnnotatedElementUtils.hasAnnotation(WithdrawalService.class, Transactional.class))
+ .as("@Transactional on the WithdrawalService class").isFalse();
+ assertThat(AnnotatedElementUtils.hasAnnotation(
+ WithdrawalService.class.getMethod("withdraw", long.class, long.class), Transactional.class))
+ .as("@Transactional on WithdrawalService.withdraw").isFalse();
+ }
+
+ /** What Spring throws for SQLSTATE 40001. LostUpdateIT proves that against a real database. */
+ private static CannotAcquireLockException serializationFailure() {
+ return new CannotAcquireLockException("could not serialize access due to concurrent update");
+ }
+
+ /**
+ * Plays back a script: each call to withdraw returns the next balance or throws the next
+ * exception. The last entry repeats for ever.
+ */
+ private static final class ScriptedWithdrawer extends Withdrawer {
+
+ private final Deque