ericrisco/rsc-harness / skills/java
java
VerifiedUse when writing, reviewing or refactoring modern Java (21+, 25 LTS) — records and sealed interfaces as algebraic data types, exhaustive pattern-matching switch over instanceof ladders, virtual-thread concurrency, structured concurrency and ScopedValue replacing ThreadLocal, Stream and Optional pipelines, compact-constructor validation, parametrized JDBC, and the Maven/Gradle build surface. NOT Spring framework wiring (that is `spring-boot`).
| File | Kind | Size |
|---|---|---|
| SKILL.md | skill md | 17.9 KB |
| evals/README.md | markdown | 1.7 KB |
| evals/cases.yaml | config | 4.5 KB |
| references/builds.md | markdown | 5.0 KB |
| references/concurrency.md | markdown | 5.0 KB |
| references/streams.md | markdown | 4.0 KB |
| scripts/verify.shexecutable | script | 3.2 KB |
references/concurrency.md
View on GitHub# Virtual threads & structured concurrency (deep)
Targets Java 21+ (virtual threads standard), Java 25 LTS for `ScopedValue` (JEP 506, final)
and `StructuredTaskScope` (JEP 505, still **preview** — needs `--enable-preview`).
## Why virtual threads change the model
A virtual thread is an ordinary `java.lang.Thread` scheduled by the JVM onto a small pool of
platform "carrier" threads. When it blocks on I/O, the JVM unmounts it and frees the carrier.
Millions can exist. The consequence: **the thread-per-request model is fast again** — you no
longer need reactive callbacks or hand-tuned pools to scale blocking I/O.
The rules:
- **One task, one virtual thread.** Submit each unit of work; do not pool virtual threads.
- **Never size them to cores.** Cores matter for CPU work, which stays on platform threads.
- **Use them for blocking calls** (JDBC, HTTP, file, RPC) — not for tight CPU loops.
## Executor wiring
```java
try (var exec = Executors.newVirtualThreadPerTaskExecutor()) {
for (var task : tasks) exec.submit(task);
} // close() blocks until every submitted task completes
```
A single `Thread.ofVirtual().start(r)` is fine for a one-off; the executor is for fan-out.
`Thread.ofVirtual().name("worker-", 0).factory()` gives a named factory for diagnostics.
## Pinning: the JEP 491 change
Before JDK 24, a virtual thread inside a `synchronized` block **pinned** its carrier — it could
not unmount, so heavy `synchronized` I/O code starved the carrier pool. **JEP 491 (JDK 24)
removed this**: virtual threads no longer pin on `synchronized`. Two consequences:
- Legacy `synchronized` code runs correctly on Loom now without rewriting to locks.
- For **long** holds still prefer `ReentrantLock` — it offers `tryLock`, fairness, and
interruptible acquisition that `synchronized` does not.
Diagnose remaining pinning (native frames, some JNI):
```bash
# JFR event jdk.VirtualThreadPinned fires on every pin; record and inspect.
java -XX:StartFlightRecording=filename=app.jfr,settings=profile -jar app.jar
jfr print --events jdk.VirtualThreadPinned app.jfr
```
## Structured concurrency (preview in 25)
`StructuredTaskScope` binds subtasks to a lexical scope: fork children, join, then the scope
guarantees all children finish or are cancelled before it closes. One failure cancels siblings.
```java
// Requires --enable-preview on Java 25 (JEP 505).
// Joiner.awaitAllSuccessfulOrThrow(): all must succeed, else the first failure cancels the rest.
import java.util.concurrent.StructuredTaskScope;
UserPage load(String id) throws Exception {
try (var scope = StructuredTaskScope.open()) { // 25-era API
var user = scope.fork(() -> fetchUser(id));
var orders= scope.fork(() -> fetchOrders(id));
scope.join(); // wait for both
return new UserPage(user.get(), orders.get());
}
}
```
The two canonical policies:
- **All-success-or-fail** (fan-out where you need every result): first failure cancels siblings.
- **Any-success** (race / hedged requests): first success cancels the slower siblings.
Note: the exact joiner/factory names have shifted across the five previews. When you write this,
confirm against the JDK you target (`java --enable-preview`) rather than trusting a fixed name.
If you cannot enable preview, `ExecutorService` + `invokeAll`/`Future` on virtual threads gives
most of the value without the lifecycle guarantees.
## ScopedValue (final in 25) replaces ThreadLocal
`ThreadLocal` is mutable, must be cleaned up (`remove()`), and its per-thread copies leak across
millions of virtual threads. `ScopedValue` is **immutable** and bound only for the dynamic extent
of a `run`/`call`, so it auto-unbinds and propagates into forked subtasks.
```java
private static final ScopedValue<RequestCtx> CTX = ScopedValue.newInstance();
ScopedValue.where(CTX, ctx).run(() -> handle(req)); // CTX.get() anywhere in the call tree
// Rebind for a nested extent:
ScopedValue.where(CTX, child).run(() -> deeper()); // outer binding restored on return
```
Migration: a `ThreadLocal<T>` field set at the top of a request becomes a `ScopedValue<T>` bound
once around the request body; every `tl.get()` becomes `sv.get()`; delete every `tl.remove()`.
## CompletableFuture vs structured
`CompletableFuture` composes async stages (`thenApply`, `thenCompose`) but has no scope: a leaked
stage runs on. Prefer structured concurrency (or a virtual-thread executor with try-with-resources)
for request-scoped fan-out so cancellation and lifetime are guaranteed. Keep `CompletableFuture`
for pipeline-style composition where you genuinely want detached, chained stages.
## When platform threads still win
- **CPU-bound** work (parsing, compression, math): a `newFixedThreadPool(cores)` is correct;
virtual threads add no parallelism for compute.
- **Throttling a scarce resource**: cap concurrency with a `Semaphore` acquired inside each
virtual task, not by shrinking a pool.
- **FFI / JNI** that pins for long stretches: measure; keep it on a bounded platform pool.
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| writing-skillsobra/superpowersUse when creating new skills, editing existing skills, or verifying skills work before deployment | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| xlsxanthropics/skillsUse this skill any time a spreadsheet file is the primary input or output. This means any task where the user wants to: open, read, edit, or fix an existing .xlsx, .xlsm, .xltx, .csv, or .tsv file (e.g., adding columns, computing formulas, formatting, charting, cleaning messy data); create a new spreadsheet from scratch or from other data sources; or convert between tabular file formats. Trigger especially when the user references a spreadsheet file by name or path — even casually (like "the xlsx in my downloads") — and wants something done to it or produced from it. Also trigger for cleaning or restructuring messy tabular data files (malformed rows, misplaced headers, junk data) into proper spreadsheets. The deliverable must be a spreadsheet file. Do NOT trigger when the primary deliverable is a Word document, HTML report, standalone Python script, database pipeline, or Google Sheets API integration, even if tabular data is involved. | Stars: 197k | Updated | Claude CodeCodex | Verified | Install |
| shipping-and-launchaddyosmani/agent-skillsPrepares production launches. Use when preparing to deploy to production, or when asking what needs to be in place before shipping. Use when you need a pre-launch checklist, when setting up monitoring, when planning a staged rollout, or when you need a rollback strategy. | Stars: 119k | Updated | Claude CodeCodex | Verified | Install |
| childhoodthedotmack/claude-memBabysit a shipped release after merge, publication, or deployment. Verify published packages, production behavior, installed plugins, and late CI or user reports until the observation window is clean; use babysit for PR readiness before release. | Stars: 118k | Updated | Claude CodeCodex | Verified | Install |