0 day streak
Code library

Code worth reading.

Hand-picked snippets across TypeScript, Python, Rust, Go, and more — each one comes with a line-by-line breakdown so you can read it like the people who wrote it.

3495 snippets · 10 languages
▶ Start learning
Java · ExpertSnippet

Structured Concurrency with StructuredTaskScope

Structured Task Scope (Preview in Java 21+) treats groups of related tasks running in different threads as a single unit of work. ShutdownOnFailure ensures that if one subtask fails, all other related virtual threads are automatically cancelled, preventing 'orphan' threads and improving observability.

snippet.java
java
1
2
3
4
5
6
7
8
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
Supplier<String> user = scope.fork(() -> fetchUser(id));
Supplier<Integer> order = scope.fork(() -> fetchOrder(id));
scope.join().throwIfFailed();
return new Dashboard(user.get(), order.get());
}
Async & ConcurrencyBest Practices
Java · ExpertSnippet

Deterministic Off-Heap Memory with Foreign Function & Memory API

The Foreign Function & Memory (FFM) API (Java 22+) provides a safe and efficient way to access memory outside the Java heap. Unlike ByteBuffer, it uses 'Arenas' for deterministic lifecycle management, avoiding the overhead of Garbage Collection for large data sets.

snippet.java
java
1
2
3
4
5
6
try (Arena arena = Arena.ofConfined()) {
MemorySegment segment = arena.allocate(1024, 1);
segment.setAtIndex(ValueLayout.JAVA_INT, 0, 42);
int value = segment.getAtIndex(ValueLayout.JAVA_INT, 0);
// Memory is released automatically when arena closes
}
Memory ManagementPerformance
Java · ExpertSnippet

Optimistic Locking with StampedLock

StampedLock offers an 'optimistic' mode where no actual lock is acquired. Instead, it returns a stamp that must be validated later. If a write occurred during the read, the validation fails and the code falls back to a traditional read lock. This significantly reduces contention in read-heavy systems.

snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
long stamp = lock.tryOptimisticRead();
int currentX = x, currentY = y;
if (!lock.validate(stamp)) {
stamp = lock.readLock();
try {
currentX = x; currentY = y;
} finally {
lock.unlockRead(stamp);
}
}
return Math.sqrt(currentX * currentX + currentY * currentY);
PerformanceAsync & Concurrency
Java · ExpertSnippet

Fine-grained Memory Barriers with VarHandles

VarHandles provide a standard way to perform atomic operations and memory fencing. 'setRelease' ensures that all prior writes in the current thread are visible to other threads performing an 'acquire' load, providing higher performance than 'volatile' for specific synchronization patterns.

snippet.java
java
1
2
3
4
5
6
7
8
9
10
private static final VarHandle STATE_VH;
static {
try {
STATE_VH = MethodHandles.lookup().findVarHandle(Node.class, "state", int.class);
} catch (Exception e) { throw new Error(e); }
}
public void releaseState() {
STATE_VH.setRelease(this, 1);
}
PerformanceAsync & Concurrency
Java · ExpertSnippet

Dynamic Invocation with MethodHandles

MethodHandles are the core mechanism behind 'invokedynamic'. They provide a more performant and type-safe alternative to traditional Reflection. Once a MethodHandle is linked, the JVM can optimize the call similarly to a direct method invocation.

snippet.java
java
1
2
3
MethodType mt = MethodType.methodType(String.class, char.class, char.class);
MethodHandle mh = MethodHandles.lookup().findVirtual(String.class, "replace", mt);
String result = (String) mh.invokeExact("hello", 'e', 'a');
PerformanceOOP
Java · ExpertSnippet

Efficient Stack Walking with StackWalker API

The StackWalker API is a performance-oriented way to inspect the call stack. Unlike Throwable.getStackTrace(), it provides a stream-based approach that lazily fetches only the required frames, making it ideal for high-performance logging or security checks.

snippet.java
java
1
2
3
4
5
6
7
StackWalker walker = StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE);
Optional<String> caller = walker.walk(frames ->
frames.skip(1)
.findFirst()
.map(StackWalker.StackFrame::getClassName)
);
PerformanceError HandlingBest Practices
Java · ExpertSnippet

Virtual Thread Pinning and ReentrantLock

Virtual threads can be 'pinned' to their carrier platform thread if they block inside a 'synchronized' block or call native methods. To maintain high throughput and scalability, developers should replace 'synchronized' with 'ReentrantLock', which allows the virtual thread to unmount correctly.

snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
private final ReentrantLock lock = new ReentrantLock();
public void safeExecution() {
lock.lock();
try {
// Blocking I/O or long task
externalService.call();
} finally {
lock.unlock();
}
}
Async & ConcurrencyPerformanceBest Practices
Java · ExpertSnippet

Nested Record Patterns for Data Extraction

Record patterns (Java 21) allow for the deep deconstruction of complex data structures directly within 'instanceof' or 'switch' statements. This eliminates boilerplate casting and accessor calls, making the code more declarative and less error-prone.

snippet.java
java
1
2
3
4
5
6
7
8
public record Customer(String name, String email) {}
public record Order(Customer customer, double total) {}
void printOrderInfo(Object obj) {
if (obj instanceof Order(Customer(var name, var email), var total)) {
System.out.printf("Customer %s (%s) spent %.2f%n", name, email, total);
}
}
SyntaxOOPBest Practices