Fairplay Interview Prep
Module 02

Java 21: the language and concurrency

All three projects are written in modern Java 21. This module covers the language features you actually used, explains the "why" behind each, and then covers concurrency (threads, atomics, executors, futures, virtual threads), which interviewers love because it is where real bugs live.

P1P2P3· about 2.5 hours

By the end you can answer

  • "What is a record, and why use one instead of a class?"
  • "What are sealed interfaces and how do they help pattern matching?"
  • "Explain the equals/hashCode contract."
  • "Why BigDecimal for money? Why inject a Clock?"
  • "What is type erasure, and why do you need TypeReference?"
  • "What is a race condition? volatile versus synchronized versus atomics?"
  • "What are virtual threads, and when should you not use them?"
  • "What happens if a task in scheduleAtFixedRate throws?"

1. How Java actually runs

You write .java source. The compiler javac turns it into bytecode (.class files), which is not machine code but instructions for a virtual machine. The JVM (Java Virtual Machine) loads the bytecode and runs it, first by interpreting it and then, for "hot" code that runs often, by compiling it to native machine code with the JIT (just-in-time) compiler. That is why Java services get faster after a warm-up, and why the Arena benchmark used a 15-second warm-up before measuring.

Memory: stack, heap and the garbage collector

Each thread has a stack holding method calls and local variables (small, fast, freed automatically when a method returns). Objects live on the shared heap. You never free objects yourself: the garbage collector (GC) finds objects no longer reachable from any live reference and reclaims them. Modern collectors (G1 is the default) are "generational": most objects die young, so the young area is collected often and cheaply.

In your projects: memory limits in containers

Every Dockerfile starts the JVM with -XX:MaxRAMPercentage=75: "use at most 75% of the memory this container is allowed as heap", leaving room for the stack, metaspace and native memory. The JVM is container-aware, so it reads the container's limit. Telemetry learned this the hard way. Without a limit, each of three detector JVMs sized its heap from the whole Docker VM and the laptop stalled. The fix was mem_limit: 1g per container in compose.yaml. This is a great "real lesson" story.

2. Classes, interfaces and immutability

A class is a blueprint; an object is an instance. An interface is a contract (method signatures) that classes implement. Your code leans heavily on interfaces at boundaries:

Useful modifiers

ModifierMeaningExample in your code
final fieldAssigned once, in the constructorEvery service: private final MatchRepository matchRepository;
final classCannot be subclassedpublic final class TelemetryTopology, DecisionPolicy, RatingCalculator
staticBelongs to the class, not to an instanceRatingCalculator.delta(...), JsonSerde.MAPPER
private constructorNobody can create instances: a "utility class"private RatingCalculator() {}, private LeaderboardEvents() {}
package-private (no modifier)Visible only inside the same packageclass StreamsWiring, static int percentile(...) (visible to the test in the same package)

Why immutability matters so much

An immutable object cannot change after construction. That gives you three things for free: it is thread-safe (nobody can modify it while another thread reads it), it is safe to share and cache, and it is easy to reason about. In AimStats.add(event) (Telemetry), adding an event returns a new AimStats instead of mutating the old one. That is exactly what a Kafka Streams aggregator wants.

3. equals, hashCode and toString

== compares references (is it the same object?). equals compares meaning (do these two objects represent the same value?). The contract:

  1. If a.equals(b) then a.hashCode() == b.hashCode(). (The reverse need not hold: different objects may share a hash.)
  2. equals must be reflexive, symmetric, transitive and consistent.

Why it matters: HashMap and HashSet first use hashCode() to pick a bucket, then equals() inside the bucket. If you override equals but not hashCode, two "equal" keys land in different buckets and map.get(key) returns null.

Common mistake: Lombok @Data on JPA entities

Arena's conventions forbid @Data, @EqualsAndHashCode and @ToString on entities. A generated hashCode over all fields changes when a field changes (or when the database assigns a value), which breaks sets the entity is already in. A generated toString walks lazy relationships and can trigger database queries, or loop forever between two entities that reference each other. Only @Getter, @Setter and @NoArgsConstructor(access = PROTECTED) are allowed. Module 07 goes deeper.

4. Records

A record (Java 16) is a class whose purpose is to carry data. You declare the components once, and Java generates the constructor, accessors (name(), not getName()), equals, hashCode and toString. All fields are private final.

arena/.../leaderboard/LeaderboardEvents.java
public record RatingChanged(UUID playerId, int rating) {}
public record RemovedFromLeaderboard(UUID playerId) {}

That one line replaces about 40 lines of a classic class. Your projects use records for: request and response DTOs (RecordMatchRequest), events, Kafka messages (MatchEvent, SuspiciousPlayer), state values in Kafka Streams stores (AimStats, IntegrityStats), configuration (ArenaProperties, DetectionProperties, JudgeSettings) and small internal tuples (private record RankedRow(UUID id, int rating) {} inside LeaderboardRebuilder).

The compact constructor: records that validate themselves

telemetry-detector/.../DetectionProperties.java
public record DetectionProperties(String detectorVersion, Duration cooldown,
        Duration integrityEmitInterval, Aimbot aimbot, Speedhack speedhack) {

    public DetectionProperties {            // compact constructor: no parameter list
        if (detectorVersion == null || detectorVersion.isBlank()) {
            throw invalid("detector-version must not be blank");
        }
        positive(cooldown, "cooldown");
        ...
    }
}

The compact constructor runs before the fields are assigned. If it throws, the object never exists, so an invalid configuration fails at startup with a message naming the property. Telemetry validates this way instead of with @Positive because Hibernate Validator has no @Positive for Duration.

What records cannot do (good interview detail)

5. Enums, EnumMap and EnumSet

An enum is a fixed set of named constants, and in Java enums are full classes that can have fields and methods:

arena/.../common/error/ErrorCode.java
public enum ErrorCode {
    VALIDATION_FAILED(HttpStatus.BAD_REQUEST, "Validation failed"),
    PLAYER_NOT_FOUND(HttpStatus.NOT_FOUND, "Player not found"),
    USERNAME_TAKEN(HttpStatus.CONFLICT, "Username taken"),
    ...

Each error code carries its HTTP status and title, so the global exception handler never needs a switch to map codes to statuses.

EnumMap and EnumSet are collections specialised for enum keys. Internally they are arrays (EnumMap) or bit vectors (EnumSet) indexed by the enum's ordinal, so they are faster and smaller than HashMap/HashSet. AccountStateMachine is built from them:

arena/.../moderation/AccountStateMachine.java
private static final Map<ModerationActionType, Set<AccountStatus>> ALLOWED_FROM =
        new EnumMap<>(ModerationActionType.class);
static {
    ALLOWED_FROM.put(ModerationActionType.FLAG, EnumSet.of(AccountStatus.ACTIVE, AccountStatus.REINSTATED));
    ALLOWED_FROM.put(ModerationActionType.NOTE, EnumSet.allOf(AccountStatus.class));
    ...
}
Gotcha

Enum.valueOf("SOMETHING") throws IllegalArgumentException for an unknown name. The Judge's PreChecks.statusOf catches it and treats an unknown status as "unknown player", so a new status added to Arena cannot crash the Judge.

6. Sealed types and pattern matching

A sealed interface (Java 17) lists exactly which types may implement it. The compiler then knows every possible case:

telemetry-detector/.../topology/ParseResult.java
public sealed interface ParseResult permits ParseResult.Parsed, ParseResult.Failed {
    record Parsed(MatchEvent event) implements ParseResult {}
    record Failed(DeadLetter deadLetter) implements ParseResult {}
}

This models "a parse either succeeded with an event or failed with a dead letter" as data, instead of throwing exceptions. The topology then branches on the type, sending Failed to the DLT and Parsed onward. A sealed type plus records is called an algebraic data type (a "sum type"), an idea borrowed from functional languages.

Pattern matching for instanceof (Java 16)

// Old style: test, then cast
if (request instanceof ServletWebRequest) {
    ServletWebRequest swr = (ServletWebRequest) request;
    return swr.getRequest().getRequestURI();
}
// New style, used in GlobalExceptionHandler.extractUri:
if (request instanceof ServletWebRequest swr) {
    return swr.getRequest().getRequestURI();
}

You will also see it in StatDistributionService: if (!(raw instanceof Object[] elements) || elements.length == 0), and in the Judge: if (failure instanceof RateLimitException rateLimited).

Switch expressions and pattern matching for switch (Java 14 and 21)

telemetry-detector/.../KafkaStreamsHealthIndicator.java
Health.Builder builder = switch (state) {
    case RUNNING -> Health.up();
    case CREATED, REBALANCING -> Health.outOfService();
    default -> Health.down();
};

A switch expression returns a value, uses arrows (no fall-through, no break), and must be exhaustive. In MatchEvent.isValid() the switch over EventType has cases for SHOT, POSITION and KILL and no default: if someone adds a fourth event type, the code stops compiling until it is handled. That is the compiler doing your code review.

Java 21 also lets you switch on types and deconstruct records (record patterns):

// Java 21 style (illustration, not from your code)
String describe(ParseResult r) {
    return switch (r) {
        case ParseResult.Parsed(MatchEvent e) -> "ok " + e.type();
        case ParseResult.Failed(DeadLetter d) -> "bad: " + d.problem();
    };   // no default needed: the interface is sealed
}

7. Generics and type erasure

Generics let a class work with any type while staying type-safe: List<Player> only accepts players, and get() returns a Player without a cast. Telemetry's serde is generic:

telemetry-common/.../json/JsonSerde.java
public final class JsonSerde<T> implements Serde<T>, Serializer<T>, Deserializer<T> {
    private final Class<T> type;
    public JsonSerde(Class<T> type) { this.type = type; }

    public T deserialize(String topic, byte[] bytes) {
        return MAPPER.readValue(bytes, type);
    }
}

Why does it need Class<T> type passed in? Because of type erasure: generic type information exists only at compile time. At runtime a JsonSerde<MatchEvent> is just a JsonSerde; Jackson cannot ask "what is T?". Passing the Class object (a "type token") gives it the answer.

For a nested generic like List<String> a Class is not enough (List.class loses the String). Jackson's trick is an anonymous subclass, whose generic superclass is kept in the bytecode:

arena/.../moderation/ModerationService.java
private static final TypeReference<List<String>> STRING_LIST_TYPE = new TypeReference<>() {};
...
return jsonMapper.readValue(evidenceJson, STRING_LIST_TYPE);

Wildcards: GenericContainer<?> means "a container of some type I don't care about". The rule of thumb PECS: "Producer Extends, Consumer Super". Use ? extends T when you only read Ts out, and ? super T when you only put Ts in.

8. Collections and their costs

TypeGet / containsOrdered?Use it whenIn your code
ArrayListget(i) O(1), contains O(n)Insertion orderDefault listMessage history in AgentLoop
HashMap / HashSetO(1) averageNoFast lookup by keyseenPlayers duplicate check in MatchService.validateRequest
TreeMapO(log n)Sorted by keyYou need a stable, sorted orderMemoizingToolExecutor.canonicalJson sorts JSON keys so {a,b} and {b,a} give the same cache key
EnumMap / EnumSetO(1), array-backedEnum orderKeys are enum constantsAccountStateMachine, EventPublisher.sentByType
ConcurrentHashMapO(1), thread-safeNoSeveral threads read and writeJudge tool cache; simulator's username→id mapping during parallel registration

9. Lambdas, functional interfaces and method references

A lambda is an anonymous function: p -> p.getId(). It can be used wherever a functional interface (an interface with exactly one abstract method) is expected. The standard ones:

InterfaceShapeExample
Supplier<T>() -> TResilience4j wraps a Supplier<Message>: Supplier<Message> call = () -> send(params);
Function<T,R>T -> RFunction.identity() in Collectors.toMap(Player::getId, Function.identity())
Predicate<T>T -> boolean.filter(Player::isEligibleForMatchAndRanking)
Consumer<T>T -> voidexecutors.forEach(ExecutorService::shutdownNow)
Runnable() -> voidnew Thread(this::runAndReport, "simulation-main")

A method reference (Player::getId, this::runAndReport) is shorthand for a lambda that just calls one method. Lambdas can only use local variables that are effectively final (never reassigned). That is why SimulationEngine copies a loop variable into int shard = k; before using it in the thread-name lambda.

10. Streams

A stream is a pipeline over a sequence of elements: a source, then lazy intermediate operations (filter, map, sorted, flatMap), then one terminal operation (toList, collect, count, forEach) that actually runs it.

arena/.../match/MatchService.java
List<UUID> sortedIds = request.participants().stream()
        .map(ParticipantRequest::playerId)   // participant -> its UUID
        .sorted()                            // sort, to lock rows in a fixed order (module 06)
        .toList();                           // unmodifiable list (Java 16)

flatMap turns each element into a stream and concatenates them. AgentLoop uses it to join all text blocks of a model response: response.content().stream().flatMap(b -> b.text().stream()).map(TextBlock::text).collect(Collectors.joining()). Here b.text() is an Optional, and Optional.stream() has zero or one element.

Stream rules interviewers check
  • A stream can be consumed only once.
  • Avoid side effects inside map/filter; that is what forEach or a plain loop is for. MatchService uses a plain for loop to update ratings because it mutates entities and publishes events: a loop is clearer there.
  • Collectors.toMap throws on duplicate keys unless you pass a merge function.
  • parallelStream() is rarely a win in a server, because it uses the shared ForkJoin common pool.

11. Optional

Optional<T> is a box that holds either a value or nothing. It forces the caller to deal with absence explicitly instead of risking a NullPointerException. Spring Data repositories return it:

arena/.../leaderboard/LeaderboardService.java
Player player = playerRepository.findById(playerId)
        .filter(Player::isEligibleForMatchAndRanking)
        .orElseThrow(() -> new ApiException(ErrorCode.PLAYER_NOT_RANKED, "Player is not ranked: " + playerId));

Read it as a sentence: "find the player; keep it only if eligible; otherwise throw PLAYER_NOT_RANKED". Guidelines:

12. Exceptions

Checked exceptions (subclasses of Exception but not RuntimeException, for example IOException or InterruptedException) must be caught or declared with throws. Unchecked exceptions (RuntimeException and subclasses) need not be. Modern Java and Spring code mostly uses unchecked exceptions for business errors.

arena/.../common/error/ApiException.java
@Getter
public class ApiException extends RuntimeException {
    private final ErrorCode errorCode;
    public ApiException(ErrorCode errorCode, String detail) {
        super(detail);
        this.errorCode = errorCode;
    }
}

One exception type plus an error-code enum keeps every business failure uniform: the handler turns any ApiException into a ProblemDetail with the right status and code.

Exception translation

A key design skill is translating low-level exceptions into ones that mean something at your layer. ResilientMessagesGateway catches the SDK's many exception types and rethrows exactly two meaningful ones: NonRetryableJudgeException (Anthropic said 400: the request itself is wrong, send the flag to the dead-letter topic) and LlmUnavailableException (circuit open, rate limited, 5xx or network failure: hold the flag and retry later). Everything above it only needs to know about these two.

try-with-resources

Anything that implements AutoCloseable can be declared in try (...) and is closed automatically, even if an exception is thrown. In your code: Kafka Streams store iterators (try (KeyValueIterator<...> all = store.all()), which must be closed or they leak native RocksDB resources), the raw HTTP response in the Judge, classpath input streams in PromptLibrary, and the virtual-thread executor in ArenaPlayerRegistrar.

Handling InterruptedException correctly

telemetry-simulator/.../engine/SimulationEngine.java
} catch (InterruptedException e) {
    Thread.currentThread().interrupt();     // restore the flag!
    log.warn("Simulation interrupted before it finished");
    completion.completeExceptionally(e);
}

Interruption is how Java asks a thread to stop. Catching the exception clears the thread's "interrupted" flag, so if you swallow it, code higher up never learns that shutdown was requested. The rule: either rethrow, or restore the flag with Thread.currentThread().interrupt().

13. Strings, text blocks and locales

14. Numbers: overflow, double and BigDecimal

15. Time, and why you inject a Clock

TypeRepresentsUse for
InstantA point on the UTC timeline (nanosecond precision)Timestamps: createdAt, token expiry
DurationAn amount of timeTTLs, window sizes, cooldowns (15m, 5s in YAML bind straight to Duration)
long epoch millisMilliseconds since 1970-01-01 UTCKafka event timestamps (MatchEvent.ts)
LocalDateTimeA date and time with no time zoneAlmost never on a server: it is ambiguous

All three projects forbid Instant.now() and System.currentTimeMillis() in main code. Instead a Clock bean is injected (ClockConfig returns Clock.systemUTC()) and code calls Instant.now(clock) or clock.millis().

Why it matters

Time-dependent logic is untestable if it reads the real clock. With an injected clock, a test passes a fixed or MutableClock and can say "advance 10 minutes" to test the cooldown, or check that a refresh token expiring at exactly "now" is rejected. Arena's TokenServiceTest bug was exactly this: the JWT decoder validated expiry against the real system clock instead of the test's fixed clock, so the test failed once the fixed date was in the past.

16. UUIDs and randomness

GeneratorPropertiesYour use
SecureRandomCryptographically strong and unpredictable; slowerRefresh tokens (32 random bytes, Base64url) in TokenService; run ids
SplittableRandomFast, seedable (same seed, same sequence), not thread-safeOne per shard, new SplittableRandom(seed + shardIndex), so runs are reproducible and threads share nothing
Random / ThreadLocalRandomGeneral purpose, not for secretsNot used for anything security-related
Interview trap

"Can I use Math.random() or Random for a password-reset token?" No: those generators are predictable. Anything an attacker must not guess needs SecureRandom.

17. Concurrency fundamentals

A thread is an independent path of execution. Threads in one JVM share the heap. Sharing is fast, and it is also dangerous, because two threads touching the same data can interfere. Three classic problems:

  1. Race condition (atomicity): count++ is really three steps (read, add, write). Two threads can both read 5 and both write 6, losing an update.
  2. Visibility: without synchronisation, a value written by one thread may sit in a CPU cache, and another thread may never see it. The Java Memory Model defines happens-before rules that guarantee visibility.
  3. Ordering: the compiler and CPU may reorder instructions unless you create a happens-before edge.

The toolbox, and where you used each

ToolGuaranteesYour code
synchronizedMutual exclusion (one thread at a time) and visibilitysynchronized (executors) { executors.add(scheduler); } in SimulationEngine: the list is touched by the main thread and by shutdown
volatileVisibility and ordering for one variable; not atomic compound operationsprivate volatile Thread mainThread;, written by one thread and read by the shutdown hook
AtomicInteger / AtomicLongLock-free atomic read-modify-write (compare-and-set)The shared matchCounter; each player's seq
LongAdderLike AtomicLong but spreads updates over cells; much faster under heavy contentionmalformedSent in EventPublisher (many shard threads increment it)
AtomicReferenceAtomically swap a referenceStatDistributionService keeps the current percentile Distribution in one; the refresh builds a new object and swaps it in
ConcurrentHashMapThread-safe map with atomic computeIfAbsent, mergeJudge tool cache; registration mapping
SemaphoreLimits how many threads do something at oncenew Semaphore(16): at most 16 registrations in flight (below)
Pattern worth naming: the immutable snapshot

StatDistributionService is read by every request thread and refreshed by a scheduler. Instead of locking, the refresh builds a complete new Distribution record off to the side and publishes it with one AtomicReference.set. Readers call current.get() and always see either the whole old snapshot or the whole new one, never a half-updated mix. This is lock-free and simple, and it is the same idea as Arena's Redis rebuild into a temp key followed by RENAME (module 08).

Confinement: the easiest thread safety

The best way to avoid shared-state bugs is to not share. In the simulator, each shard owns its players, its own SplittableRandom and its own malformed-record injector, and runs on its own single thread. The comment on PlayerState says the sequence counter is "only advanced by the shard thread that owns the player". Kafka Streams uses the same idea at scale: each task owns its partitions and state stores, and only one thread ever touches them (module 10).

18. Executors, scheduled tasks and CompletableFuture

Creating raw threads by hand is rarely right. An ExecutorService manages a pool of threads; you submit tasks and get Futures back. Always shut executors down: shutdown() stops accepting work and lets running tasks finish, awaitTermination(...) waits, and shutdownNow() interrupts them.

The scheduleAtFixedRate trap

telemetry-simulator/.../engine/ShardWorker.java
/** An exception thrown from a task given to scheduleAtFixedRate silently
 *  cancels every later run, which would freeze this shard's players without
 *  any visible error, so each tick is guarded and the next one still happens. */
@Override
public void run() {
    try {
        tick();
    } catch (Throwable t) {
        log.error("Shard {} tick failed", shardIndex, t);
    }
}

This is a classic interview question, and you have a real example of it. If a periodic task throws, the ScheduledExecutorService stores the exception in the task's Future (which nobody reads) and cancels all future runs. Nothing is logged. The shard would simply stop producing events. Catching Throwable at the top of a periodic task is the standard defence.

CompletableFuture

A CompletableFuture<T> is a value that will be available later, which you can chain (thenApply, thenCompose), combine (allOf) or wait for (join, get). Spring Kafka's KafkaTemplate.send(...) returns one that completes when the broker acknowledges the record.

telemetry-simulator/.../engine/SimulationEngine.java
List<CompletableFuture<?>> setup = new ArrayList<>(population.size() * 2);
for (PlayerState player : population) {
    setup.add(publisher.publishProfile(...));
    setup.add(publisher.publishGroundTruth(...));
}
CompletableFuture.allOf(setup.toArray(CompletableFuture[]::new)).join();

This sends 2,000 records concurrently and then waits until all are acknowledged, so the run never starts before every profile is safely in Kafka. In the Judge, publisher.publish(verdict).join() waits for the broker's acknowledgement before the listener returns, because only then is it safe to let the offset be committed.

19. Virtual threads (Java 21)

A classic Java thread (a platform thread) is a wrapper around an operating-system thread. OS threads are expensive: about 1 MB of stack each, and costly to create and switch. A server that blocks one thread per request (waiting on a database or HTTP call) runs out of threads long before it runs out of CPU.

A virtual thread is a lightweight thread managed by the JVM. Millions can exist. When a virtual thread blocks on I/O, the JVM unmounts it from its carrier (a platform thread in a small ForkJoin pool) and runs another virtual thread on that carrier. When the I/O completes, it is mounted again. You keep simple, blocking, readable code, and get the scalability of asynchronous code.

In your projects
  • Arena and Judge set spring.threads.virtual.enabled: true, so Tomcat (Arena) and the Spring task executors run work on virtual threads. Arena's request threads spend most of their time waiting on PostgreSQL and Redis, the ideal case.
  • The simulator's registrar registers 1,000 players over HTTP:
    Semaphore permits = new Semaphore(concurrency);          // 16
    try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
        for (PlayerState player : todo) {
            futures.add(executor.submit(() -> {
                permits.acquire();
                try { mapping.put(player.username(), client.register(player)); }
                finally { permits.release(); }
                return null;
            }));
        }
        ...
    }   // close() waits for all tasks
    One cheap virtual thread per player, but a Semaphore caps the number of concurrent calls at 16. Virtual threads make threads cheap; they do not make Arena faster. Each registration hashes a password with bcrypt, which is CPU-heavy on Arena's side, so unbounded concurrency would just overload it.
  • The simulator's shards deliberately use platform threads (newSingleThreadScheduledExecutor, one per shard). The work is CPU-bound event generation on a fixed tick, and each shard must stay on its own dedicated thread because its state (random generator, players) is confined to it.

When virtual threads do not help, or hurt

20. Java version timeline (what came when)

VersionFeatureSeen in your code
8 (2014)Lambdas, streams, Optional, java.timeEverywhere
10var local type inferencevar aim = props.aimbot(); in TelemetryTopology
14Switch expressionsKafkaStreamsHealthIndicator, MatchEvent.isValid
15Text blocks, String.formattedSQL in LeaderboardRebuilder, the verdict schema
16Records, pattern matching for instanceof, Stream.toList()Everywhere
17 (LTS)Sealed classes, HexFormatParseResult, token hashing
21 (LTS)Virtual threads, pattern matching for switch, record patterns, sequenced collections, Math.clampRegistrar, getLast(), percentile clamp

LTS means long-term support. Companies standardise on LTS versions (8, 11, 17, 21, 25), which is why Java 21 is a sensible choice for a portfolio.

21. Interview questions

What is a record and when would you not use one? Basic

A record is a concise, immutable data carrier. Java generates the canonical constructor, accessors, equals, hashCode and toString from the component list. I use records for DTOs, events, Kafka messages and configuration, and I validate in the compact constructor so invalid objects can't exist. I would not use one for a JPA entity (it needs a no-arg constructor, mutable state and identity-based equality) or when I need inheritance. Also remember that immutability is shallow: PlayerState holds an AtomicLong whose value changes.

Explain the equals/hashCode contract and what breaks if you violate it. Basic

Equal objects must have equal hash codes. Hash-based collections use hashCode to find a bucket and equals to find the entry inside it. Override equals without hashCode and two equal keys land in different buckets, so lookups fail and sets hold duplicates. A related trap: if a field used in hashCode changes while the object sits in a HashSet, the object becomes unreachable in its own set. That is one reason my JPA entities don't use Lombok's @EqualsAndHashCode.

What does sealed give you? Intermediate

A closed set of subtypes known to the compiler. That enables exhaustive switch without a default: adding a new subtype breaks compilation wherever it isn't handled. In Telemetry, ParseResult is sealed with Parsed and Failed records, so a parse outcome is data rather than an exception, and the topology branches on it to route failures to the dead-letter topic.

What is type erasure, and how does Jackson deserialise a List<String>? Intermediate

Generic type arguments are checked at compile time and removed from the bytecode, so at runtime a List<String> is just a List. Jackson therefore needs the type passed explicitly: a Class<T> for simple types (as in Telemetry's JsonSerde), or a TypeReference<List<String>> for nested generics. The TypeReference trick works because an anonymous subclass's generic superclass is recorded in its class file, so Jackson can read it with reflection. Arena's ModerationService uses one to read the evidence list.

Why BigDecimal for money, and what's the equals trap? Basic

double is binary floating point and cannot represent most decimal fractions exactly, so errors accumulate (0.1 + 0.2 != 0.3). BigDecimal is exact with explicit rounding modes. The Judge's CostCalculator prices tokens with BigDecimal and rounds to 6 decimals HALF_UP. The trap: equals compares scale too, so 0.80 and 0.8 are not equal. Use compareTo, as Arena does for the confidence floor.

Why inject a Clock instead of calling Instant.now()? Basic

Determinism and testability. Any logic involving time (token expiry, cooldowns, windows, latency) becomes testable when the test controls time with a fixed or mutable clock. All three projects ban direct Instant.now(). I hit a real bug this way: a JWT decoder in a test validated expiry against the system clock instead of the test clock, so the test started failing once the fixed date fell into the past.

volatile vs synchronized vs AtomicLong: when do you use each? Intermediate

volatile guarantees visibility and ordering for a single variable, but not atomicity of compound actions: volatile int x; x++ can still lose updates. I use it for a flag or a reference written by one thread and read by others, like the simulator's mainThread. synchronized gives mutual exclusion plus visibility for a block of code: use it to protect a compound invariant, like adding to a shared list. Atomics (AtomicLong, AtomicReference) give lock-free atomic updates of one value via compare-and-set: use them for counters and for swapping an immutable snapshot. Under very heavy write contention on a counter, LongAdder beats AtomicLong because it spreads updates across cells.

What happens if a task scheduled with scheduleAtFixedRate throws an exception? Deep

Its future completes exceptionally and all later executions are silently cancelled. Unless someone calls get() on the returned future, nothing is logged. In Telemetry's simulator that would freeze a shard's players with no error. ShardWorker.run() wraps each tick in try/catch (Throwable) and logs, so one bad tick never stops the next.

What are virtual threads? Why did you cap the registrar at 16 concurrent calls if threads are cheap? Deep

Virtual threads are JVM-managed lightweight threads. When one blocks on I/O, it unmounts from its carrier platform thread so another can run, which lets blocking-style code scale to huge numbers of concurrent tasks. They make waiting cheap, but they don't increase the capacity of whatever you're waiting on. Each registration makes Arena hash a password with bcrypt, which is deliberately CPU-expensive, and Arena has a 20-connection database pool. Unbounded concurrency would just overload Arena and cause timeouts, so a Semaphore(16) bounds in-flight calls while still using one virtual thread per task. Pooling virtual threads would be the wrong tool; a semaphore is the idiomatic limiter.

What is pinning in virtual threads? Deep

On Java 21, a virtual thread that blocks while holding a monitor (inside synchronized) or during a native call cannot unmount, so it occupies its carrier thread. With enough pinned threads the small carrier pool is exhausted and throughput collapses. Mitigations: use ReentrantLock instead of synchronized around blocking I/O, and detect it with -Djdk.tracePinnedThreads or JFR events. JDK 24 (JEP 491) removed pinning for synchronized.

How do you handle InterruptedException? Intermediate

Never swallow it. Either let it propagate, or restore the interrupt flag with Thread.currentThread().interrupt() before returning, so code further up the stack (an executor shutting down, for example) knows a stop was requested. SimulationEngine.runAndReport does exactly this and also completes its future exceptionally, so waiters are not left hanging.

Checked vs unchecked exceptions: which do you use for business errors and why? Basic

Unchecked. Business errors like "player not found" are handled centrally (Arena's @RestControllerAdvice maps every ApiException to a ProblemDetail), so forcing every method in between to declare them only adds noise. Spring's @Transactional also rolls back by default only on unchecked exceptions. Checked exceptions suit recoverable conditions the immediate caller must handle, such as I/O. I also translate low-level exceptions into meaningful ones at boundaries, as ResilientMessagesGateway maps many SDK exceptions to just "non-retryable" and "unavailable".

Why does your binary search use (lo + hi) >>> 1? Curveball

To avoid integer overflow. (lo + hi) / 2 overflows to a negative number if lo + hi exceeds Integer.MAX_VALUE. The unsigned right shift treats the sum as unsigned, so it still yields the correct midpoint. With 101 cut points it can't overflow here, but it is the correct idiom, and it was a real bug in the JDK's Arrays.binarySearch for years.

Two PlayerState records with identical fields compare unequal. Why? Curveball

Record equals compares each component with that component's own equals. One component is an AtomicLong, which does not override equals, so it compares by identity. Two separately created counters are never equal, even when they hold the same number. Tests therefore compare a projection of the fields that matter instead of the records themselves.

What is the difference between the JDK, JRE and JVM, and why does your Dockerfile use both? Basic

The JVM runs bytecode. The JRE is the JVM plus the standard libraries needed to run programs. The JDK adds the compiler and tools needed to build. The multi-stage Dockerfile builds with temurin:21-jdk, then copies only the jar into a temurin:21-jre image. The final image is smaller and has a smaller attack surface (no compiler), and it runs as a non-root user.

Why did three detector containers freeze a 16 GB laptop, and how did you fix it? Intermediate

Without a container memory limit, each JVM's ergonomics sized its maximum heap from the whole Docker VM's memory (MaxRAMPercentage=75 of about 7.7 GB), so three JVMs together could claim far more than physically available, and the VM started swapping until Docker stopped responding. Setting mem_limit: 1g per container lets the container-aware JVM size its heap to 75% of 1 GB. Lesson: always give JVM containers an explicit limit.

22. Quick quiz

1. What does a record's compact constructor let you do?

It runs before assignment, so throwing there means an invalid instance never exists. Telemetry's settings records fail startup this way.

2. volatile long counter; counter++ from many threads is:

Use AtomicLong.incrementAndGet() or LongAdder.increment() for counters.

3. Which is the right generator for a refresh token?

Tokens must be unpredictable. TokenService uses 32 bytes from SecureRandom.

4. new BigDecimal("0.80").compareTo(new BigDecimal("0.8")) returns:

compareTo ignores scale; equals would return false.

5. Virtual threads help most when the work is:

They make blocking cheap. CPU-bound work gains nothing, and on Java 21 synchronized blocks can pin the carrier.

6. A periodic task in scheduleAtFixedRate throws once. Afterwards:

That's why ShardWorker.run() catches Throwable.

7. Why does JsonSerde<T> take a Class<T> in its constructor?

A type token carries what erasure removed.

23. Cheat sheet

Language

  • Record: immutable data carrier; validate in the compact constructor; shallow immutability; not for JPA entities.
  • Sealed + records: a closed set of cases, giving exhaustive switches. Example: ParseResult.
  • equals/hashCode: equal objects, equal hashes. No @Data on entities.
  • Erasure: pass Class<T> or a TypeReference.
  • Optional: a return type only; orElseThrow, map, filter.
  • Money: BigDecimal + compareTo + an explicit RoundingMode.
  • Time: Instant/Duration, UTC, an injected Clock.
  • Random: SecureRandom for secrets; seeded SplittableRandom per thread for reproducible simulation.

Concurrency

  • Race (atomicity), visibility, ordering. Tools: synchronized, volatile, atomics, LongAdder, ConcurrentHashMap, Semaphore.
  • Immutable snapshot + AtomicReference = lock-free reads.
  • Confinement (one owner thread) is the easiest form of thread safety.
  • A periodic task that throws is cancelled silently; catch Throwable.
  • Restore the interrupt flag.
  • Virtual threads: for I/O-bound work; bound concurrency with a Semaphore; don't pool them; beware pinning on Java 21.

JVM

  • Bytecode, interpreter, then the JIT warms up hot code. Heap + GC; a stack per thread.
  • Containers: -XX:MaxRAMPercentage=75 + an explicit memory limit.
Saved in this browser.