Add experienced-2-3y module: 31 scenario questions (core Java, collections/streams, concurrency, Spring Boot 4.2, JPA N+1, REST problem details, SQL) with 7 asserting tests and 8 transcripts

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b6u469kis46DspusiL
This commit is contained in:
Ankur Mhatre
2026-11-22 02:01:04 +05:30
co-authored by Claude Sonnet 5.5
parent 4180e746ef
commit 76012dd8c3
36 changed files with 1401 additions and 0 deletions
+1
View File
@@ -28,6 +28,7 @@ One module per article. This repository currently holds:
| [`splitwise`](splitwise/) | Low-Level Design: Splitwise (Expense Sharing) in Java | this commit | | [`splitwise`](splitwise/) | Low-Level Design: Splitwise (Expense Sharing) in Java | this commit |
| [`graph-algorithms`](graph-algorithms/) | Graph Algorithms in Java: Dijkstra, Topological Sort and Union-Find | this commit | | [`graph-algorithms`](graph-algorithms/) | Graph Algorithms in Java: Dijkstra, Topological Sort and Union-Find | this commit |
| [`elevator`](elevator/) | Low-Level Design: Elevator System in Java (State Pattern and Scheduling) | this commit | | [`elevator`](elevator/) | Low-Level Design: Elevator System in Java (State Pattern and Scheduling) | this commit |
| [`experienced-2-3y`](experienced-2-3y/) | Java Interview Questions for 2 to 3 Years Experience (Scenario-Based, with Answers) | this commit |
## `collections` module ## `collections` module
+38
View File
@@ -0,0 +1,38 @@
# experienced-2-3y
Runnable companion for the ankurm.com article
[Java Interview Questions for 2 to 3 Years Experience (Scenario-Based, with Answers)](https://ankurm.com/java-interview-questions-for-2-3-years-experience/).
Thirty-one scenario questions across core Java, collections and streams, concurrency, Spring Boot, REST, JPA and SQL.
Every question that makes a claim about behaviour has a demo here, and a test that asserts the line the article quotes
and writes it to `output/`. There is no `docs/` folder on purpose: the explanations live in the article.
| Component | Version | Verified against |
|---|---|---|
| JDK | 25.0.5.1+2 (Temurin, LTS) | `java -version` |
| Spring Boot | 4.2.0 (Spring Framework 7.1.0, Spring Data JPA 4.2.0) | `maven-metadata.xml` on Maven Central; `4.2.0` was published there on 2026-11-19 |
| Hibernate ORM | 7.4.15.Final | `mvn dependency:list` |
| H2 | 2.5.252 | `mvn dependency:list` |
| JUnit | 6.1.3 | `mvn dependency:list` |
| Maven | 3.9.11 | `mvn -version` |
```bash
export JAVA_HOME=/path/to/jdk-25 && export PATH="$JAVA_HOME/bin:$PATH"
cd experienced-2-3y
mvn test # 7 tests (3 plain Java, 4 Spring); rewrites output/01-07
./scripts/run-all.sh # also regenerates output/08 (javac's own error for src/broken/)
```
| Where | Questions | Transcript |
|---|---|---|
| `core/CoreQa` | 1-6 core Java | `output/01-core-java.txt` |
| `coll/CollectionsQa` | 7-12 collections, streams, Optional | `output/02-collections-streams.txt` |
| `conc/ConcurrencyQa` | 13-17 concurrency | `output/03-concurrency.txt` |
| `spring/` (`Invoice`, `Counters`, `TxProbe`, `Transfers`) + `SpringCoreScenariosTest` | 18-21 Spring | `output/04-spring-di-tx.txt` |
| `spring/` (`CustomerApi`, `ApiErrors`) + `RestScenariosTest` | 22-24 REST | `output/06-rest.txt` |
| `spring/` (`Customer`, `CustomerOrder`, `OrderReports`) + `JpaScenariosTest` | 25-27 JPA | `output/05-jpa.txt` |
| `SqlScenariosTest` | 28-31 SQL | `output/07-sql.txt` |
| `src/broken/NonExhaustiveSwitch.java` | 6 (compile error) | `output/08-compile-errors.txt` |
`03-concurrency.txt` comes from deliberately racy code: the tests assert that updates were lost, but the exact
numbers differ on every run, so the article treats them as indicative. `src/broken/` is excluded from the Maven build.
+22
View File
@@ -0,0 +1,22 @@
== Q1: equals() without hashCode() ==
equal points in HashSet (equals only): size = 2
equal points in HashSet (record): size = 1
== Q2: unboxing null ==
int n = map.get("pencil") -> NullPointerException
useDefault ? maybe : 0 -> NullPointerException (type of ?: is int)
useDefault ? maybe : Integer.valueOf(0) -> null
map.getOrDefault("pencil", 0) -> 0
== Q3: overridable method in a constructor ==
Child.describe sees constantLabel = child, label = null
Child.describe sees constantLabel = child, label = child
== Q4: defensive copy ==
leaky roster after outside changes: [Asha, Ravi, Intruder, Another]
safe roster after outside change: [Asha, Ravi]
safe roster add -> UnsupportedOperationException
== Q5: keep the cause ==
without cause: invalid port configuration | cause = null
with cause: invalid port configuration | cause = java.lang.NumberFormatException: For input string: "80a"
== Q6: sealed interface + pattern switch ==
Card[last4=4242] -> card ending 4242
Upi[vpa=asha@bank] -> UPI asha@bank
Cod[] -> cash on delivery
@@ -0,0 +1,21 @@
== Q7: TreeSet and a comparator that says 'equal' ==
TreeSet by length only: [fig, apple] (3 words added, size 2)
length then natural: [fig, apple, grape]
== Q8: List<Integer>.remove(int) vs remove(Object) ==
remove(1) -> [10, 30]
remove(Integer.valueOf(10)) -> [20, 30]
== Q9: Collectors.toMap with a duplicate key ==
toMap(city, amount) -> IllegalStateException: Duplicate key Pune (attempted merging values 100 and 250)
toMap with Integer::sum -> {Mumbai=300, Pune=350}
groupingBy + counting -> {Mumbai=1, Pune=2}
== Q10: streams are lazy ==
no terminal operation: elements touched = 0
findFirst() on evens: result = 2, elements touched = 2
== Q11: Optional.orElse vs orElseGet ==
orElse(expensiveDefault()) -> default computed 1 time(s)
orElseGet(expensiveDefault) -> default computed 0 time(s)
== Q12: comparator chain with nulls ==
Employee[name=Kiran, dept=Eng, salary=80000]
Employee[name=Meera, dept=Sales, salary=120000]
Employee[name=Asha, dept=Sales, salary=90000]
Employee[name=Ravi, dept=null, salary=70000]
@@ -0,0 +1,16 @@
== Q13: volatile is visibility, not atomicity ==
volatile int, 8 threads x 100000 increments: LOST UPDATES (expected 800000)
AtomicInteger, same work: 800000
== Q14: exceptions inside an ExecutorService ==
after submit(): no output yet, future.isDone() = true
future.get() -> ExecutionException, cause = java.lang.IllegalStateException: boom from submit
uncaught handler on worker: boom from execute
== Q15: ConcurrentHashMap is safe per call, not per sequence ==
containsKey/put/get sequence: LOST UPDATES (expected 80000)
merge(key, 1, Integer::sum): 80000
== Q16: ReentrantLock.tryLock with a timeout ==
tryLock(50 ms) while another thread holds it -> false
tryLock() after the holder released it -> true
== Q17: 10,000 blocking tasks on virtual threads ==
tasks completed = 10000, ran on virtual threads = 10000
finished in under 5 seconds: true
@@ -0,0 +1,16 @@
== Q18: constructor injection ==
Invoice built with plain new and a lambda, no Spring context: total(100) = 110.0
Invoice from the context (FlatGst 18%): total(100) = 118.0
== Q19: singleton state is shared ==
two getBean(SingletonCounter) calls return the same object: true
caller A next() = 1, caller B next() = 2
two getBean(PrototypeCounter) calls return the same object: false
caller A next() = 1, caller B next() = 1
== Q20: @Transactional and self-invocation ==
TxProbe injected as a Spring proxy: true
probe.inner() -> transaction active = true
probe.outerCallsInner() -> transaction active = false
== Q21: which exceptions roll back ==
RuntimeException after save -> rows added = 0
checked IOException after save -> rows added = 1
checked + rollbackFor = Exception.class -> rows added = 0
+14
View File
@@ -0,0 +1,14 @@
== Q25: N+1 selects ==
data: 5 customers, 12 orders (4 customers x 3 orders, plus one customer with none)
lazy loop (default) : total = 2400, SQL statements = 6
JOIN FETCH query : total = 2400, SQL statements = 1
@EntityGraph("orders") : total = 2400, SQL statements = 1
== Q26: LazyInitializationException ==
no @Transactional around the loop -> LazyInitializationException
message: Cannot lazily initialize collection of role 'com.ankurm.interviewlab.exp23.spring.Customer.orders' with key '1' (no session)
== Q27: a DTO projection with LEFT JOIN ==
OrderTotal[name=Asha, total=600]
OrderTotal[name=Kiran, total=600]
OrderTotal[name=Meera, total=600]
OrderTotal[name=Nobody, total=0]
OrderTotal[name=Ravi, total=600]
+13
View File
@@ -0,0 +1,13 @@
== Q22: create returns 201 and a Location header ==
POST /customers {"name":"Asha"}
status = 201
Location = /customers/1
body = {"id":1,"name":"Asha"}
== Q23: bean validation turns into 400 ==
POST /customers {"name":"A"} (@Size(min = 2))
status = 400
body = {"detail":"Invalid request content.","status":400,"title":"Bad Request"}
== Q24: a missing resource is a 404 problem response ==
GET /customers/99
status = 404
body = {"detail":"customer 99 not found","status":404,"title":"Customer not found"}
+19
View File
@@ -0,0 +1,19 @@
data: employee salaries are 120000, 120000, 90000, 80000, 70000 (two people tie for the top)
== Q28: second highest salary ==
ORDER BY salary DESC OFFSET 1 (no DISTINCT) -> 120000 <- the tie makes this the top salary again
SELECT DISTINCT ... OFFSET 1 -> 90000
MAX(salary) WHERE salary < MAX(salary) -> 90000
DENSE_RANK() = 2 -> 90000
== Q29: duplicates ==
emails seen more than once:
[email protected] x3
[email protected] x2
DELETE ... NOT IN (SELECT MIN(id) ... GROUP BY email) removed 3 rows; left: [1, 2, 4]
== Q30: INNER vs LEFT JOIN, COUNT(*) vs COUNT(col), WHERE vs ON ==
departments (id 30 'Ops' has no employees)
INNER JOIN departments returned: 2 LEFT JOIN: 3
Ops: COUNT(*) = 1, COUNT(e.id) = 0 <- COUNT(*) counts the NULL-extended row
LEFT JOIN + WHERE e.salary > 100000 keeps 2 departments; the same filter in ON keeps 3
== Q31: what an index changes in the plan ==
without an index: SELECT "PUBLIC"."BIG_SIGNUP"."ID", "PUBLIC"."BIG_SIGNUP"."EMAIL" FROM "PUBLIC"."BIG_SIGNUP" /* PUBLIC.BIG_SIGNUP.tableScan */ WHERE "EMAIL" = '[email protected]'
with idx_big_email: SELECT "PUBLIC"."BIG_SIGNUP"."ID", "PUBLIC"."BIG_SIGNUP"."EMAIL" FROM "PUBLIC"."BIG_SIGNUP" /* PUBLIC.IDX_BIG_EMAIL: EMAIL = '[email protected]' */ WHERE "EMAIL" = '[email protected]'
@@ -0,0 +1,5 @@
=== javac NonExhaustiveSwitch.java ===
NonExhaustiveSwitch.java:9: error: the switch expression does not cover all possible input values
return switch (p) {
^
1 error
+73
View File
@@ -0,0 +1,73 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>4.2.0</version>
<relativePath/>
</parent>
<groupId>com.ankurm.interviewlab</groupId>
<artifactId>experienced-2-3y</artifactId>
<version>1.0.0</version>
<name>java-interview-lab :: experienced-2-3y</name>
<description>
Runnable companion for ankurm.com's "Java Interview Questions for 2 to 3 Years Experience":
core Java, collections and streams, concurrency, Spring Boot, JPA, REST and SQL scenarios.
Tests assert what each demo prints and write the transcripts the article quotes.
</description>
<properties>
<java.version>25</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>-Xmx512m -Duser.timezone=UTC -Dfile.encoding=UTF-8</argLine>
</configuration>
</plugin>
</plugins>
</build>
</project>
+9
View File
@@ -0,0 +1,9 @@
#!/usr/bin/env bash
# Compiles the file in src/broken/ (NOT part of the Maven build) and captures javac's own message.
set -uo pipefail
cd "$(dirname "$0")/../src/broken"
out=../../output/08-compile-errors.txt
: > "$out"
echo "=== javac NonExhaustiveSwitch.java ===" >> "$out"
javac --release 25 -d /tmp/exp23-broken NonExhaustiveSwitch.java 2>&1 | grep -v '^Picked up' >> "$out"
cat "$out"
+9
View File
@@ -0,0 +1,9 @@
#!/usr/bin/env bash
# Regenerates every file in output/. Needs JDK 25 and Maven (first Maven run online).
# 01-07 are written by JUnit tests that assert the lines they write; 08 is javac's own output for src/broken/.
# 03 contains counts from deliberately racy code: the tests assert that updates were lost, the exact numbers drift per run.
set -euo pipefail
cd "$(dirname "$0")/.."
mvn -B -q test
./scripts/compile-errors.sh > /dev/null
echo "done:"; ls -1 output
@@ -0,0 +1,14 @@
/** Must NOT compile: the switch forgets Cod, and Payment is sealed, so the compiler knows. */
public class NonExhaustiveSwitch {
sealed interface Payment permits Card, Upi, Cod {}
record Card(String last4) implements Payment {}
record Upi(String vpa) implements Payment {}
record Cod() implements Payment {}
static String describe(Payment p) {
return switch (p) {
case Card c -> "card " + c.last4();
case Upi u -> "UPI " + u.vpa();
};
}
}
@@ -0,0 +1,11 @@
package com.ankurm.interviewlab.exp23;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class InterviewApplication {
public static void main(String[] args) {
SpringApplication.run(InterviewApplication.class, args);
}
}
@@ -0,0 +1,107 @@
package com.ankurm.interviewlab.exp23.coll;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.TreeSet;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
/** Collections, streams and Optional scenarios 7-12. */
public final class CollectionsQa {
private CollectionsQa() {}
static void q7TreeSetComparator() {
System.out.println("== Q7: TreeSet and a comparator that says 'equal' ==");
TreeSet<String> byLength = new TreeSet<>(Comparator.comparingInt(String::length));
byLength.add("apple");
byLength.add("grape");
byLength.add("fig");
System.out.println("TreeSet by length only: " + byLength + " (3 words added, size " + byLength.size() + ")");
TreeSet<String> fixed = new TreeSet<>(Comparator.comparingInt(String::length).thenComparing(Comparator.naturalOrder()));
fixed.addAll(List.of("apple", "grape", "fig"));
System.out.println("length then natural: " + fixed);
}
static void q8RemoveOverload() {
System.out.println("== Q8: List<Integer>.remove(int) vs remove(Object) ==");
List<Integer> byIndex = new ArrayList<>(List.of(10, 20, 30));
byIndex.remove(1);
System.out.println("remove(1) -> " + byIndex);
List<Integer> byValue = new ArrayList<>(List.of(10, 20, 30));
byValue.remove(Integer.valueOf(10));
System.out.println("remove(Integer.valueOf(10)) -> " + byValue);
}
record Sale(String city, int amount) {}
static void q9Collectors() {
System.out.println("== Q9: Collectors.toMap with a duplicate key ==");
List<Sale> sales = List.of(new Sale("Pune", 100), new Sale("Mumbai", 300), new Sale("Pune", 250));
try {
sales.stream().collect(Collectors.toMap(Sale::city, Sale::amount));
} catch (IllegalStateException e) {
System.out.println("toMap(city, amount) -> IllegalStateException: " + e.getMessage());
}
Map<String, Integer> merged = sales.stream()
.collect(Collectors.toMap(Sale::city, Sale::amount, Integer::sum, java.util.TreeMap::new));
System.out.println("toMap with Integer::sum -> " + merged);
Map<String, Long> counts = sales.stream()
.collect(Collectors.groupingBy(Sale::city, java.util.TreeMap::new, Collectors.counting()));
System.out.println("groupingBy + counting -> " + counts);
}
static void q10StreamLaziness() {
System.out.println("== Q10: streams are lazy ==");
AtomicInteger touched = new AtomicInteger();
IntStream.rangeClosed(1, 10).boxed().peek(x -> touched.incrementAndGet()).filter(x -> x % 2 == 0);
System.out.println("no terminal operation: elements touched = " + touched.get());
touched.set(0);
Optional<Integer> first = IntStream.rangeClosed(1, 10).boxed()
.peek(x -> touched.incrementAndGet()).filter(x -> x % 2 == 0).findFirst();
System.out.println("findFirst() on evens: result = " + first.get() + ", elements touched = " + touched.get());
}
static final AtomicInteger EXPENSIVE_CALLS = new AtomicInteger();
static String expensiveDefault() {
EXPENSIVE_CALLS.incrementAndGet();
return "computed-default";
}
static void q11OptionalOrElse() {
System.out.println("== Q11: Optional.orElse vs orElseGet ==");
Optional<String> cached = Optional.of("cached");
EXPENSIVE_CALLS.set(0);
cached.orElse(expensiveDefault());
System.out.println("orElse(expensiveDefault()) -> default computed " + EXPENSIVE_CALLS.get() + " time(s)");
EXPENSIVE_CALLS.set(0);
cached.orElseGet(CollectionsQa::expensiveDefault);
System.out.println("orElseGet(expensiveDefault) -> default computed " + EXPENSIVE_CALLS.get() + " time(s)");
}
record Employee(String name, String dept, int salary) {}
static void q12ComparatorChain() {
System.out.println("== Q12: comparator chain with nulls ==");
List<Employee> staff = new ArrayList<>(List.of(
new Employee("Asha", "Sales", 90_000), new Employee("Ravi", null, 70_000),
new Employee("Meera", "Sales", 120_000), new Employee("Kiran", "Eng", 80_000)));
staff.sort(Comparator.comparing(Employee::dept, Comparator.nullsLast(Comparator.naturalOrder()))
.thenComparing(Employee::salary, Comparator.reverseOrder()));
staff.forEach(e -> System.out.println(" " + e));
}
public static void run() {
q7TreeSetComparator();
q8RemoveOverload();
q9Collectors();
q10StreamLaziness();
q11OptionalOrElse();
q12ComparatorChain();
}
}
@@ -0,0 +1,139 @@
package com.ankurm.interviewlab.exp23.conc;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;
/** Concurrency scenarios 13-17. */
public final class ConcurrencyQa {
private ConcurrencyQa() {}
static volatile int volatileCounter;
static final AtomicInteger atomicCounter = new AtomicInteger();
static void runThreads(int threads, Runnable body) throws InterruptedException {
List<Thread> all = new ArrayList<>();
for (int i = 0; i < threads; i++) all.add(Thread.ofPlatform().start(body));
for (Thread t : all) t.join();
}
/** Returns the volatile total; 8 threads x 100,000 increments = 800,000 expected. */
public static int volatileIncrements() throws InterruptedException {
volatileCounter = 0;
runThreads(8, () -> { for (int i = 0; i < 100_000; i++) volatileCounter++; });
return volatileCounter;
}
public static int atomicIncrements() throws InterruptedException {
atomicCounter.set(0);
runThreads(8, () -> { for (int i = 0; i < 100_000; i++) atomicCounter.incrementAndGet(); });
return atomicCounter.get();
}
static void q13Volatile() throws InterruptedException {
System.out.println("== Q13: volatile is visibility, not atomicity ==");
int v = volatileIncrements();
for (int attempt = 1; attempt < 20 && v == 800_000; attempt++) v = volatileIncrements();
System.out.println("volatile int, 8 threads x 100000 increments: " + (v < 800_000 ? "LOST UPDATES" : "no loss seen this run")
+ " (expected 800000)");
System.out.println("AtomicInteger, same work: " + atomicIncrements());
}
static void q14Executor() throws Exception {
System.out.println("== Q14: exceptions inside an ExecutorService ==");
ExecutorService pool = Executors.newFixedThreadPool(1, r -> {
Thread t = new Thread(r, "worker");
t.setUncaughtExceptionHandler((th, ex) -> System.out.println("uncaught handler on " + th.getName() + ": " + ex.getMessage()));
return t;
});
Future<?> submitted = pool.submit(() -> { throw new IllegalStateException("boom from submit"); });
pool.submit(() -> { }).get();
System.out.println("after submit(): no output yet, future.isDone() = " + submitted.isDone());
try {
submitted.get();
} catch (ExecutionException e) {
System.out.println("future.get() -> ExecutionException, cause = " + e.getCause());
}
CountDownLatch seen = new CountDownLatch(1);
pool.execute(() -> { try { throw new IllegalStateException("boom from execute"); } finally { seen.countDown(); } });
seen.await();
pool.shutdown();
pool.awaitTermination(2, TimeUnit.SECONDS);
Thread.sleep(100);
}
/** Returns {checkThenPut total, merge total}; 8 threads x 10,000 updates of one key = 80,000. */
public static int[] mapCounters() throws InterruptedException {
ConcurrentHashMap<String, Integer> racy = new ConcurrentHashMap<>();
ConcurrentHashMap<String, Integer> atomic = new ConcurrentHashMap<>();
runThreads(8, () -> {
for (int i = 0; i < 10_000; i++) {
if (!racy.containsKey("hits")) racy.put("hits", 1); else racy.put("hits", racy.get("hits") + 1);
atomic.merge("hits", 1, Integer::sum);
}
});
return new int[] {racy.get("hits"), atomic.get("hits")};
}
static void q15ConcurrentHashMap() throws InterruptedException {
System.out.println("== Q15: ConcurrentHashMap is safe per call, not per sequence ==");
int[] r = mapCounters();
for (int attempt = 1; attempt < 20 && r[0] == 80_000; attempt++) r = mapCounters();
System.out.println("containsKey/put/get sequence: " + (r[0] < 80_000 ? "LOST UPDATES" : "no loss seen this run") + " (expected 80000)");
System.out.println("merge(key, 1, Integer::sum): " + r[1]);
}
static void q16TryLock() throws Exception {
System.out.println("== Q16: ReentrantLock.tryLock with a timeout ==");
ReentrantLock lock = new ReentrantLock();
CountDownLatch held = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
Thread holder = Thread.ofPlatform().start(() -> {
lock.lock();
try { held.countDown(); release.await(); } catch (InterruptedException ignored) { } finally { lock.unlock(); }
});
held.await();
boolean got = lock.tryLock(50, TimeUnit.MILLISECONDS);
System.out.println("tryLock(50 ms) while another thread holds it -> " + got);
release.countDown();
holder.join();
System.out.println("tryLock() after the holder released it -> " + lock.tryLock());
lock.unlock();
}
static void q17VirtualThreads() throws Exception {
System.out.println("== Q17: 10,000 blocking tasks on virtual threads ==");
AtomicInteger done = new AtomicInteger();
AtomicInteger virtual = new AtomicInteger();
long start = System.nanoTime();
try (ExecutorService pool = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 10_000; i++) {
pool.submit(() -> {
try { Thread.sleep(100); } catch (InterruptedException ignored) { }
if (Thread.currentThread().isVirtual()) virtual.incrementAndGet();
done.incrementAndGet();
});
}
}
long ms = (System.nanoTime() - start) / 1_000_000;
System.out.println("tasks completed = " + done.get() + ", ran on virtual threads = " + virtual.get());
System.out.println("finished in under 5 seconds: " + (ms < 5_000));
}
public static void run() throws Exception {
q13Volatile();
q14Executor();
q15ConcurrentHashMap();
q16TryLock();
q17VirtualThreads();
}
}
@@ -0,0 +1,178 @@
package com.ankurm.interviewlab.exp23.core;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/** Core Java scenarios 1-6. Each method prints what the article quotes. */
public final class CoreQa {
private CoreQa() {}
// ---- Q1: equals() without hashCode() ----------------------------------------------------
static final class BrokenPoint {
final int x, y;
BrokenPoint(int x, int y) { this.x = x; this.y = y; }
@Override public boolean equals(Object o) {
return o instanceof BrokenPoint p && p.x == x && p.y == y;
}
// hashCode() deliberately NOT overridden
}
record GoodPoint(int x, int y) {}
static void q1EqualsWithoutHashCode() {
System.out.println("== Q1: equals() without hashCode() ==");
Set<BrokenPoint> broken = new HashSet<>();
broken.add(new BrokenPoint(1, 2));
broken.add(new BrokenPoint(1, 2));
System.out.println("equal points in HashSet (equals only): size = " + broken.size());
Set<GoodPoint> good = new HashSet<>();
good.add(new GoodPoint(1, 2));
good.add(new GoodPoint(1, 2));
System.out.println("equal points in HashSet (record): size = " + good.size());
}
// ---- Q2: unboxing NullPointerException ---------------------------------------------------
static void q2Unboxing() {
System.out.println("== Q2: unboxing null ==");
Map<String, Integer> stock = new HashMap<>();
stock.put("pen", 10);
try {
int n = stock.get("pencil");
System.out.println("stock = " + n);
} catch (NullPointerException e) {
System.out.println("int n = map.get(\"pencil\") -> NullPointerException");
}
Integer maybe = null;
boolean useDefault = true;
try {
Integer r = useDefault ? maybe : 0;
System.out.println("ternary gave " + r);
} catch (NullPointerException e) {
System.out.println("useDefault ? maybe : 0 -> NullPointerException (type of ?: is int)");
}
Integer safe = useDefault ? maybe : Integer.valueOf(0);
System.out.println("useDefault ? maybe : Integer.valueOf(0) -> " + safe);
System.out.println("map.getOrDefault(\"pencil\", 0) -> " + stock.getOrDefault("pencil", 0));
}
// ---- Q3: overridable method called from a constructor ------------------------------------
static class Base {
Base() { describe(); }
void describe() { System.out.println("Base.describe"); }
}
static class Child extends Base {
private final String constantLabel = "child"; // a constant variable: the compiler inlines it
private final String label; // assigned in the constructor, after super()
Child() { super(); this.label = "child"; }
@Override void describe() {
System.out.println("Child.describe sees constantLabel = " + constantLabel + ", label = " + label);
}
}
static void q3ConstructorCallsOverridable() {
System.out.println("== Q3: overridable method in a constructor ==");
Child c = new Child();
c.describe();
}
// ---- Q4: defensive copies ----------------------------------------------------------------
static final class LeakyRoster {
private final List<String> members;
LeakyRoster(List<String> members) { this.members = members; }
List<String> members() { return members; }
}
record SafeRoster(List<String> members) {
SafeRoster { members = List.copyOf(members); }
}
static void q4DefensiveCopy() {
System.out.println("== Q4: defensive copy ==");
List<String> source = new ArrayList<>(List.of("Asha", "Ravi"));
LeakyRoster leaky = new LeakyRoster(source);
source.add("Intruder");
leaky.members().add("Another");
System.out.println("leaky roster after outside changes: " + leaky.members());
List<String> source2 = new ArrayList<>(List.of("Asha", "Ravi"));
SafeRoster safe = new SafeRoster(source2);
source2.add("Intruder");
System.out.println("safe roster after outside change: " + safe.members());
try {
safe.members().add("Another");
} catch (UnsupportedOperationException e) {
System.out.println("safe roster add -> UnsupportedOperationException");
}
}
// ---- Q5: swallowing the cause ------------------------------------------------------------
static int parsePort(String raw) {
return Integer.parseInt(raw);
}
static void loadLosingCause(String raw) {
try {
parsePort(raw);
} catch (NumberFormatException e) {
throw new IllegalStateException("invalid port configuration");
}
}
static void loadKeepingCause(String raw) {
try {
parsePort(raw);
} catch (NumberFormatException e) {
throw new IllegalStateException("invalid port configuration", e);
}
}
static void q5ExceptionCause() {
System.out.println("== Q5: keep the cause ==");
try {
loadLosingCause("80a");
} catch (IllegalStateException e) {
System.out.println("without cause: " + e.getMessage() + " | cause = " + e.getCause());
}
try {
loadKeepingCause("80a");
} catch (IllegalStateException e) {
System.out.println("with cause: " + e.getMessage() + " | cause = " + e.getCause());
}
}
// ---- Q6: sealed types, records and pattern-matching switch --------------------------------
sealed interface Payment permits Card, Upi, Cod {}
record Card(String last4) implements Payment {}
record Upi(String vpa) implements Payment {}
record Cod() implements Payment {}
static String describe(Payment p) {
return switch (p) {
case Card c -> "card ending " + c.last4();
case Upi u -> "UPI " + u.vpa();
case Cod c -> "cash on delivery";
};
}
static void q6SealedSwitch() {
System.out.println("== Q6: sealed interface + pattern switch ==");
for (Payment p : List.<Payment>of(new Card("4242"), new Upi("asha@bank"), new Cod())) {
System.out.println(p + " -> " + describe(p));
}
}
public static void run() {
q1EqualsWithoutHashCode();
q2Unboxing();
q3ConstructorCallsOverridable();
q4DefensiveCopy();
q5ExceptionCause();
q6SealedSwitch();
}
}
@@ -0,0 +1,19 @@
package com.ankurm.interviewlab.exp23.spring;
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
/** One place that turns exceptions into RFC 9457 problem responses. */
@RestControllerAdvice
public class ApiErrors extends ResponseEntityExceptionHandler {
@ExceptionHandler(CustomerApi.CustomerNotFound.class)
ProblemDetail notFound(CustomerApi.CustomerNotFound e) {
ProblemDetail pd = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, e.getMessage());
pd.setTitle("Customer not found");
return pd;
}
}
@@ -0,0 +1,24 @@
package com.ankurm.interviewlab.exp23.spring;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
/** Singleton vs prototype: Spring creates ONE singleton and shares it across every caller. */
public final class Counters {
private Counters() {}
@Component
public static class SingletonCounter {
private int count;
public int next() { return ++count; }
}
@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public static class PrototypeCounter {
private int count;
public int next() { return ++count; }
}
}
@@ -0,0 +1,26 @@
package com.ankurm.interviewlab.exp23.spring;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.OneToMany;
import java.util.ArrayList;
import java.util.List;
@Entity
public class Customer {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@OneToMany(mappedBy = "customer")
private List<CustomerOrder> orders = new ArrayList<>();
protected Customer() {}
public Customer(String name) { this.name = name; }
public Long getId() { return id; }
public String getName() { return name; }
public List<CustomerOrder> getOrders() { return orders; }
}
@@ -0,0 +1,42 @@
package com.ankurm.interviewlab.exp23.spring;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import java.net.URI;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/customers")
public class CustomerApi {
public record CreateCustomer(@NotBlank @Size(min = 2, max = 40) String name) {}
public record CustomerView(Long id, String name) {}
public static class CustomerNotFound extends RuntimeException {
public CustomerNotFound(Long id) { super("customer " + id + " not found"); }
}
private final CustomerRepository customers;
public CustomerApi(CustomerRepository customers) { this.customers = customers; }
@PostMapping
public ResponseEntity<CustomerView> create(@Valid @RequestBody CreateCustomer body) {
Customer saved = customers.save(new Customer(body.name()));
return ResponseEntity.created(URI.create("/customers/" + saved.getId()))
.body(new CustomerView(saved.getId(), saved.getName()));
}
@GetMapping("/{id}")
public CustomerView get(@PathVariable Long id) {
Customer c = customers.findById(id).orElseThrow(() -> new CustomerNotFound(id));
return new CustomerView(c.getId(), c.getName());
}
}
@@ -0,0 +1,25 @@
package com.ankurm.interviewlab.exp23.spring;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
@Entity
@Table(name = "customer_order")
public class CustomerOrder {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private int amount;
@ManyToOne(fetch = FetchType.LAZY)
private Customer customer;
protected CustomerOrder() {}
public CustomerOrder(Customer customer, int amount) { this.customer = customer; this.amount = amount; }
public int getAmount() { return amount; }
}
@@ -0,0 +1,5 @@
package com.ankurm.interviewlab.exp23.spring;
import org.springframework.data.jpa.repository.JpaRepository;
public interface CustomerOrderRepository extends JpaRepository<CustomerOrder, Long> {}
@@ -0,0 +1,21 @@
package com.ankurm.interviewlab.exp23.spring;
import java.util.List;
import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
public interface CustomerRepository extends JpaRepository<Customer, Long> {
@Query("select distinct c from Customer c join fetch c.orders")
List<Customer> findAllWithOrdersJoinFetch();
@EntityGraph(attributePaths = "orders")
List<Customer> findAllByOrderByIdAsc();
record OrderTotal(String name, long total) {}
@Query("select new com.ankurm.interviewlab.exp23.spring.CustomerRepository$OrderTotal(c.name, coalesce(sum(o.amount), 0)) "
+ "from Customer c left join c.orders o group by c.name order by c.name")
List<OrderTotal> totals();
}
@@ -0,0 +1,21 @@
package com.ankurm.interviewlab.exp23.spring;
import org.springframework.stereotype.Service;
/** Constructor injection: the dependency is a final field and the class can be built with plain new. */
@Service
public class Invoice {
public interface TaxPolicy { double rateFor(double amount); }
private final TaxPolicy tax;
public Invoice(TaxPolicy tax) { this.tax = tax; }
public double total(double amount) { return amount + amount * tax.rateFor(amount); }
@Service
static class FlatGst implements TaxPolicy {
@Override public double rateFor(double amount) { return 0.18; }
}
}
@@ -0,0 +1,53 @@
package com.ankurm.interviewlab.exp23.spring;
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/** The JPA scenarios: N+1 selects, the fixes, and LazyInitializationException. */
@Service
public class OrderReports {
private final CustomerRepository customers;
public OrderReports(CustomerRepository customers) { this.customers = customers; }
/** 1 query for customers, then 1 per customer when the lazy collection is touched. */
@Transactional(readOnly = true)
public int sumNaive() {
int sum = 0;
for (Customer c : customers.findAll()) {
for (CustomerOrder o : c.getOrders()) sum += o.getAmount();
}
return sum;
}
@Transactional(readOnly = true)
public int sumJoinFetch() {
int sum = 0;
for (Customer c : customers.findAllWithOrdersJoinFetch()) {
for (CustomerOrder o : c.getOrders()) sum += o.getAmount();
}
return sum;
}
@Transactional(readOnly = true)
public int sumEntityGraph() {
int sum = 0;
for (Customer c : customers.findAllByOrderByIdAsc()) {
for (CustomerOrder o : c.getOrders()) sum += o.getAmount();
}
return sum;
}
/** No @Transactional: the session is closed when findAll() returns, so touching orders fails. */
public int sumWithoutTransaction() {
int sum = 0;
for (Customer c : customers.findAll()) {
for (CustomerOrder o : c.getOrders()) sum += o.getAmount();
}
return sum;
}
public List<CustomerRepository.OrderTotal> projection() { return customers.totals(); }
}
@@ -0,0 +1,32 @@
package com.ankurm.interviewlab.exp23.spring;
import java.io.IOException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/** Which exceptions roll a transaction back. */
@Service
public class Transfers {
private final CustomerRepository customers;
public Transfers(CustomerRepository customers) { this.customers = customers; }
@Transactional
public void failWithRuntime(String name) {
customers.save(new Customer(name));
throw new IllegalStateException("runtime failure after save");
}
@Transactional
public void failWithChecked(String name) throws IOException {
customers.save(new Customer(name));
throw new IOException("checked failure after save");
}
@Transactional(rollbackFor = Exception.class)
public void failWithCheckedRollbackFor(String name) throws IOException {
customers.save(new Customer(name));
throw new IOException("checked failure after save");
}
}
@@ -0,0 +1,16 @@
package com.ankurm.interviewlab.exp23.spring;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronizationManager;
/** Shows when @Transactional is applied: only for calls that go through the Spring proxy. */
@Service
public class TxProbe {
/** Not transactional itself; calls inner() on "this", which is the raw object, not the proxy. */
public boolean outerCallsInner() { return inner(); }
@Transactional
public boolean inner() { return TransactionSynchronizationManager.isActualTransactionActive(); }
}
@@ -0,0 +1,6 @@
spring.datasource.url=jdbc:h2:mem:interview;DB_CLOSE_DELAY=-1
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.open-in-view=false
spring.jpa.properties.hibernate.generate_statistics=true
spring.main.banner-mode=off
logging.level.root=WARN
@@ -0,0 +1,74 @@
package com.ankurm.interviewlab.exp23;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import com.ankurm.interviewlab.exp23.spring.Customer;
import com.ankurm.interviewlab.exp23.spring.CustomerOrder;
import com.ankurm.interviewlab.exp23.spring.CustomerOrderRepository;
import com.ankurm.interviewlab.exp23.spring.CustomerRepository;
import com.ankurm.interviewlab.exp23.spring.OrderReports;
import jakarta.persistence.EntityManagerFactory;
import org.hibernate.LazyInitializationException;
import org.hibernate.SessionFactory;
import org.hibernate.stat.Statistics;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.DirtiesContext;
@SpringBootTest(properties = "spring.datasource.url=jdbc:h2:mem:jpascenarios")
@DirtiesContext
class JpaScenariosTest {
@Autowired CustomerRepository customers;
@Autowired CustomerOrderRepository orders;
@Autowired OrderReports reports;
@Autowired EntityManagerFactory emf;
@Test
void nPlusOneAndLazyInitialization() throws Exception {
for (String name : new String[] {"Asha", "Ravi", "Meera", "Kiran"}) {
Customer c = customers.save(new Customer(name));
for (int i = 1; i <= 3; i++) orders.save(new CustomerOrder(c, i * 100));
}
customers.save(new Customer("Nobody")); // a customer with no orders, for the LEFT JOIN projection
Statistics stats = emf.unwrap(SessionFactory.class).getStatistics();
Transcript t = new Transcript("05-jpa.txt");
t.line("== Q25: N+1 selects ==");
t.line("data: " + customers.count() + " customers, " + orders.count() + " orders (4 customers x 3 orders, plus one customer with none)");
stats.clear();
int naive = reports.sumNaive();
long naiveStatements = stats.getPrepareStatementCount();
t.line("lazy loop (default) : total = " + naive + ", SQL statements = " + naiveStatements);
stats.clear();
int joinFetch = reports.sumJoinFetch();
long joinStatements = stats.getPrepareStatementCount();
t.line("JOIN FETCH query : total = " + joinFetch + ", SQL statements = " + joinStatements);
stats.clear();
int graph = reports.sumEntityGraph();
long graphStatements = stats.getPrepareStatementCount();
t.line("@EntityGraph(\"orders\") : total = " + graph + ", SQL statements = " + graphStatements);
assertEquals(2400, naive);
assertEquals(naive, joinFetch);
assertEquals(naive, graph);
assertEquals(1 + 5, naiveStatements); // 1 for customers + 1 per customer (5 customers)
assertEquals(1, joinStatements);
assertEquals(1, graphStatements);
t.line("== Q26: LazyInitializationException ==");
LazyInitializationException e = assertThrows(LazyInitializationException.class, () -> reports.sumWithoutTransaction());
t.line("no @Transactional around the loop -> " + e.getClass().getSimpleName());
t.line("message: " + e.getMessage());
t.line("== Q27: a DTO projection with LEFT JOIN ==");
reports.projection().forEach(p -> t.line(" " + p));
assertEquals(5, reports.projection().size());
t.write();
}
}
@@ -0,0 +1,80 @@
package com.ankurm.interviewlab.exp23;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.ankurm.interviewlab.exp23.coll.CollectionsQa;
import com.ankurm.interviewlab.exp23.conc.ConcurrencyQa;
import com.ankurm.interviewlab.exp23.core.CoreQa;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.concurrent.Callable;
import org.junit.jupiter.api.Test;
/** Runs the plain-Java question classes, asserts the claims the article makes, writes output/01-03. */
class PlainTranscriptsTest {
private static String capture(String file, Callable<Void> body) throws Exception {
PrintStream original = System.out;
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
System.setOut(new PrintStream(buffer, true, StandardCharsets.UTF_8));
try { body.call(); } finally { System.setOut(original); }
String text = buffer.toString(StandardCharsets.UTF_8);
Files.createDirectories(Path.of("output"));
Files.writeString(Path.of("output", file), text);
return text;
}
private static void has(String text, String... expected) {
for (String e : expected) assertTrue(text.contains(e), "missing: " + e + "\n" + text);
}
@Test
void core() throws Exception {
String t = capture("01-core-java.txt", () -> { CoreQa.run(); return null; });
has(t, "(equals only): size = 2", "(record): size = 1",
"int n = map.get(\"pencil\") -> NullPointerException",
"useDefault ? maybe : 0 -> NullPointerException (type of ?: is int)",
"Child.describe sees constantLabel = child, label = null",
"leaky roster after outside changes: [Asha, Ravi, Intruder, Another]",
"safe roster after outside change: [Asha, Ravi]",
"without cause: invalid port configuration | cause = null",
"with cause: invalid port configuration | cause = java.lang.NumberFormatException: For input string: \"80a\"",
"Card[last4=4242] -> card ending 4242", "Cod[] -> cash on delivery");
}
@Test
void collectionsAndStreams() throws Exception {
String t = capture("02-collections-streams.txt", () -> { CollectionsQa.run(); return null; });
has(t, "TreeSet by length only: [fig, apple] (3 words added, size 2)",
"length then natural: [fig, apple, grape]",
"remove(1) -> [10, 30]", "remove(Integer.valueOf(10)) -> [20, 30]",
"Duplicate key Pune (attempted merging values 100 and 250)",
"toMap with Integer::sum -> {Mumbai=300, Pune=350}", "groupingBy + counting -> {Mumbai=1, Pune=2}",
"no terminal operation: elements touched = 0", "findFirst() on evens: result = 2, elements touched = 2",
"orElse(expensiveDefault()) -> default computed 1 time(s)",
"orElseGet(expensiveDefault) -> default computed 0 time(s)");
assertTrue(t.indexOf("Employee[name=Kiran") < t.indexOf("Employee[name=Meera"));
assertTrue(t.indexOf("Employee[name=Meera") < t.indexOf("Employee[name=Asha"));
assertTrue(t.indexOf("Employee[name=Asha") < t.indexOf("Employee[name=Ravi"));
}
@Test
void concurrency() throws Exception {
String t = capture("03-concurrency.txt", () -> { ConcurrencyQa.run(); return null; });
has(t, "volatile int, 8 threads x 100000 increments: LOST UPDATES (expected 800000)",
"AtomicInteger, same work: 800000",
"after submit(): no output yet, future.isDone() = true",
"future.get() -> ExecutionException, cause = java.lang.IllegalStateException: boom from submit",
"uncaught handler on worker: boom from execute",
"containsKey/put/get sequence: LOST UPDATES (expected 80000)",
"merge(key, 1, Integer::sum): 80000",
"tryLock(50 ms) while another thread holds it -> false",
"tryLock() after the holder released it -> true",
"tasks completed = 10000, ran on virtual threads = 10000", "finished in under 5 seconds: true");
assertEquals(800_000, ConcurrencyQa.atomicIncrements());
}
}
@@ -0,0 +1,55 @@
package com.ankurm.interviewlab.exp23;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
import org.springframework.http.MediaType;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
@SpringBootTest(properties = "spring.datasource.url=jdbc:h2:mem:restscenarios")
@AutoConfigureMockMvc
@DirtiesContext
class RestScenariosTest {
@Autowired MockMvc mvc;
private MvcResult post(String json) throws Exception {
return mvc.perform(MockMvcRequestBuilders.post("/customers").contentType(MediaType.APPLICATION_JSON).content(json)).andReturn();
}
@Test
void statusCodesValidationAndProblemDetail() throws Exception {
Transcript t = new Transcript("06-rest.txt");
t.line("== Q22: create returns 201 and a Location header ==");
MvcResult created = post("{\"name\":\"Asha\"}");
t.line("POST /customers {\"name\":\"Asha\"}");
t.line(" status = " + created.getResponse().getStatus());
t.line(" Location = " + created.getResponse().getHeader("Location"));
t.line(" body = " + created.getResponse().getContentAsString());
assertEquals(201, created.getResponse().getStatus());
assertEquals("/customers/1", created.getResponse().getHeader("Location"));
t.line("== Q23: bean validation turns into 400 ==");
MvcResult bad = post("{\"name\":\"A\"}");
t.line("POST /customers {\"name\":\"A\"} (@Size(min = 2))");
t.line(" status = " + bad.getResponse().getStatus());
t.line(" body = " + bad.getResponse().getContentAsString());
assertEquals(400, bad.getResponse().getStatus());
t.line("== Q24: a missing resource is a 404 problem response ==");
MvcResult missing = mvc.perform(MockMvcRequestBuilders.get("/customers/99")).andReturn();
t.line("GET /customers/99");
t.line(" status = " + missing.getResponse().getStatus());
t.line(" body = " + missing.getResponse().getContentAsString());
assertEquals(404, missing.getResponse().getStatus());
assertTrue(missing.getResponse().getContentAsString().contains("customer 99 not found"));
t.write();
}
}
@@ -0,0 +1,87 @@
package com.ankurm.interviewlab.exp23;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.ankurm.interviewlab.exp23.spring.Counters;
import com.ankurm.interviewlab.exp23.spring.CustomerRepository;
import com.ankurm.interviewlab.exp23.spring.Invoice;
import com.ankurm.interviewlab.exp23.spring.Transfers;
import com.ankurm.interviewlab.exp23.spring.TxProbe;
import java.io.IOException;
import org.junit.jupiter.api.Test;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.test.annotation.DirtiesContext;
@SpringBootTest(properties = "spring.datasource.url=jdbc:h2:mem:springcore")
@DirtiesContext
class SpringCoreScenariosTest {
@Autowired ApplicationContext ctx;
@Autowired TxProbe probe;
@Autowired Transfers transfers;
@Autowired CustomerRepository customers;
@Test
void injectionScopesProxiesAndRollback() throws Exception {
Transcript t = new Transcript("04-spring-di-tx.txt");
// Q18 constructor injection
t.line("== Q18: constructor injection ==");
Invoice plain = new Invoice(amount -> 0.10);
t.line("Invoice built with plain new and a lambda, no Spring context: total(100) = " + plain.total(100));
assertEquals(110.0, plain.total(100), 0.0001);
Invoice managed = ctx.getBean(Invoice.class);
t.line("Invoice from the context (FlatGst 18%): total(100) = " + managed.total(100));
assertEquals(118.0, managed.total(100), 0.0001);
// Q19 singleton state
t.line("== Q19: singleton state is shared ==");
Counters.SingletonCounter s1 = ctx.getBean(Counters.SingletonCounter.class);
Counters.SingletonCounter s2 = ctx.getBean(Counters.SingletonCounter.class);
assertSame(s1, s2);
t.line("two getBean(SingletonCounter) calls return the same object: " + (s1 == s2));
t.line("caller A next() = " + s1.next() + ", caller B next() = " + s2.next());
Counters.PrototypeCounter p1 = ctx.getBean(Counters.PrototypeCounter.class);
Counters.PrototypeCounter p2 = ctx.getBean(Counters.PrototypeCounter.class);
assertNotSame(p1, p2);
t.line("two getBean(PrototypeCounter) calls return the same object: " + (p1 == p2));
t.line("caller A next() = " + p1.next() + ", caller B next() = " + p2.next());
// Q20 self-invocation
t.line("== Q20: @Transactional and self-invocation ==");
assertTrue(AopUtils.isAopProxy(probe));
t.line("TxProbe injected as a Spring proxy: " + AopUtils.isAopProxy(probe));
boolean viaProxy = probe.inner();
boolean viaThis = probe.outerCallsInner();
t.line("probe.inner() -> transaction active = " + viaProxy);
t.line("probe.outerCallsInner() -> transaction active = " + viaThis);
assertTrue(viaProxy);
assertFalse(viaThis);
// Q21 rollback rules
t.line("== Q21: which exceptions roll back ==");
long before = customers.count();
assertThrows(IllegalStateException.class, () -> transfers.failWithRuntime("runtime"));
long afterRuntime = customers.count();
t.line("RuntimeException after save -> rows added = " + (afterRuntime - before));
assertThrows(IOException.class, () -> transfers.failWithChecked("checked"));
long afterChecked = customers.count();
t.line("checked IOException after save -> rows added = " + (afterChecked - afterRuntime));
assertThrows(IOException.class, () -> transfers.failWithCheckedRollbackFor("checked-rollbackFor"));
long afterRollbackFor = customers.count();
t.line("checked + rollbackFor = Exception.class -> rows added = " + (afterRollbackFor - afterChecked));
assertEquals(0, afterRuntime - before);
assertEquals(1, afterChecked - afterRuntime);
assertEquals(0, afterRollbackFor - afterChecked);
t.write();
}
}
@@ -0,0 +1,88 @@
package com.ankurm.interviewlab.exp23;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.simple.JdbcClient;
import org.springframework.test.annotation.DirtiesContext;
@SpringBootTest(properties = "spring.datasource.url=jdbc:h2:mem:sqlscenarios")
@DirtiesContext
class SqlScenariosTest {
@Autowired JdbcClient jdbc;
private void exec(String sql) { jdbc.sql(sql).update(); }
private List<Map<String, Object>> rows(String sql) { return jdbc.sql(sql).query().listOfRows(); }
@Test
void sqlScenarios() throws Exception {
exec("CREATE TABLE department (id INT PRIMARY KEY, name VARCHAR(20))");
exec("CREATE TABLE employee (id INT PRIMARY KEY, name VARCHAR(20), dept_id INT, salary INT)");
exec("INSERT INTO department VALUES (10,'Eng'),(20,'Sales'),(30,'Ops')");
exec("INSERT INTO employee VALUES (1,'Asha',10,90000),(2,'Ravi',10,120000),(3,'Meera',20,120000),(4,'Kiran',20,80000),(5,'Dev',20,70000)");
exec("CREATE TABLE signup (id INT PRIMARY KEY, email VARCHAR(40))");
exec("INSERT INTO signup VALUES (1,'[email protected]'),(2,'[email protected]'),(3,'[email protected]'),(4,'[email protected]'),(5,'[email protected]'),(6,'[email protected]')");
Transcript t = new Transcript("07-sql.txt");
t.line("data: employee salaries are 120000, 120000, 90000, 80000, 70000 (two people tie for the top)");
t.line("== Q28: second highest salary ==");
Object offset = rows("SELECT DISTINCT salary FROM employee ORDER BY salary DESC OFFSET 1 ROW FETCH FIRST 1 ROW ONLY").get(0).get("SALARY");
Object offsetNoDistinct = rows("SELECT salary FROM employee ORDER BY salary DESC OFFSET 1 ROW FETCH FIRST 1 ROW ONLY").get(0).get("SALARY");
Object sub = rows("SELECT MAX(salary) AS s FROM employee WHERE salary < (SELECT MAX(salary) FROM employee)").get(0).get("S");
Object dense = rows("SELECT salary FROM (SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) r FROM employee) WHERE r = 2").get(0).get("SALARY");
t.line("ORDER BY salary DESC OFFSET 1 (no DISTINCT) -> " + offsetNoDistinct + " <- the tie makes this the top salary again");
t.line("SELECT DISTINCT ... OFFSET 1 -> " + offset);
t.line("MAX(salary) WHERE salary < MAX(salary) -> " + sub);
t.line("DENSE_RANK() = 2 -> " + dense);
assertEquals(120000, offsetNoDistinct);
assertEquals(90000, offset);
assertEquals(90000, sub);
assertEquals(90000, dense);
t.line("== Q29: duplicates ==");
t.line("emails seen more than once:");
rows("SELECT email, COUNT(*) AS n FROM signup GROUP BY email HAVING COUNT(*) > 1 ORDER BY email")
.forEach(r -> t.line(" " + r.get("EMAIL") + " x" + r.get("N")));
int deleted = jdbc.sql("DELETE FROM signup WHERE id NOT IN (SELECT MIN(id) FROM signup GROUP BY email)").update();
t.line("DELETE ... NOT IN (SELECT MIN(id) ... GROUP BY email) removed " + deleted + " rows; left: "
+ rows("SELECT id FROM signup ORDER BY id").stream().map(r -> String.valueOf(r.get("ID"))).toList());
assertEquals(3, deleted);
t.line("== Q30: INNER vs LEFT JOIN, COUNT(*) vs COUNT(col), WHERE vs ON ==");
t.line("departments (id 30 'Ops' has no employees)");
long inner = rows("SELECT d.name FROM department d JOIN employee e ON e.dept_id = d.id GROUP BY d.name").size();
long left = rows("SELECT d.name FROM department d LEFT JOIN employee e ON e.dept_id = d.id GROUP BY d.name").size();
t.line("INNER JOIN departments returned: " + inner + " LEFT JOIN: " + left);
Map<String, Object> ops = rows("SELECT d.name, COUNT(*) AS star, COUNT(e.id) AS col FROM department d LEFT JOIN employee e ON e.dept_id = d.id WHERE d.id = 30 GROUP BY d.name").get(0);
t.line("Ops: COUNT(*) = " + ops.get("STAR") + ", COUNT(e.id) = " + ops.get("COL") + " <- COUNT(*) counts the NULL-extended row");
long whereFilter = rows("SELECT d.name FROM department d LEFT JOIN employee e ON e.dept_id = d.id WHERE e.salary > 100000 GROUP BY d.name").size();
long onFilter = rows("SELECT d.name FROM department d LEFT JOIN employee e ON e.dept_id = d.id AND e.salary > 100000 GROUP BY d.name").size();
t.line("LEFT JOIN + WHERE e.salary > 100000 keeps " + whereFilter + " departments; the same filter in ON keeps " + onFilter);
assertEquals(2, inner);
assertEquals(3, left);
assertEquals(1, ops.get("COL") instanceof Number n ? ((Number) ops.get("STAR")).intValue() : -1);
assertEquals(0L, ((Number) ops.get("COL")).longValue());
assertEquals(2, whereFilter);
assertEquals(3, onFilter);
t.line("== Q31: what an index changes in the plan ==");
exec("CREATE TABLE big_signup (id INT PRIMARY KEY, email VARCHAR(40))");
exec("INSERT INTO big_signup SELECT x, 'user' || x || '@x.com' FROM SYSTEM_RANGE(1, 20000)");
String before = String.valueOf(rows("EXPLAIN SELECT * FROM big_signup WHERE email = '[email protected]'").get(0).values().iterator().next());
exec("CREATE INDEX idx_big_email ON big_signup(email)");
String after = String.valueOf(rows("EXPLAIN SELECT * FROM big_signup WHERE email = '[email protected]'").get(0).values().iterator().next());
t.line("without an index: " + before.replace("\n", " "));
t.line("with idx_big_email: " + after.replace("\n", " "));
assertTrue(before.contains("tableScan"));
assertTrue(after.contains("IDX_BIG_EMAIL"));
t.write();
}
}
@@ -0,0 +1,22 @@
package com.ankurm.interviewlab.exp23;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
/** Collects lines and writes output/NN-*.txt; the test asserts the same values it writes. */
final class Transcript {
private final StringBuilder text = new StringBuilder();
private final String file;
Transcript(String file) { this.file = file; }
Transcript line(String s) { text.append(s).append('\n'); return this; }
String write() throws IOException {
Files.createDirectories(Path.of("output"));
Files.writeString(Path.of("output", file), text.toString(), StandardCharsets.UTF_8);
return text.toString();
}
}