Java Examples

Page 2 of 7

Browse Java examples

javaSnippet

Double NaN Never Equals Itself

NaN compares false against everything including itself: use Double.isNaN for detection and Double.compare for ordering, which treats NaN as equal to itself.

javaSnippet

Read Symbolic Link Target Path

Create a symlink and read back the raw target stored inside it with Files.readSymbolicLink, keeping toRealPath as the follow-the-link view of the same path.

javaSnippet

Lock Ordering Avoids Deadlock

Order lock acquisition by account id so opposite-direction transfers queue on the same locks instead of holding one and waiting for the other forever.

javaSnippet

PlusMonths Month-End Clamping

plusMonths and plusYears clamp to the last valid day instead of overflowing into the next month, and the clamp is not reversible when months are added back.

javaSnippet

Poison Pill Queue Shutdown

End a consumer loop by sending a sentinel object through the queue: the producer appends it after the last job and the consumer breaks on identity.

javaSnippet

Private Final Lock Object

Guard mutable list state with a private final lock object instead of synchronized(this) so outside code cannot interfere with the monitor.

javaSnippet

Record Overloaded Constructors

Add secondary record constructors that delegate to the canonical one, deriving checkout dates and parsing ISO strings without breaking component accessors.

javaSnippet

Parse Fixed Width Column Text

Extract fields from fixed-width records with per-column start and end offsets, keeping short lines honest instead of throwing past the line end.

javaSnippet

Token Bucket Rate Limiter (Java)

Refill tokens continuously from elapsed time and admit only when one is available, so bursts up to capacity pass while steady traffic stays capped.

javaSnippet

UUID Version 7 Time Ordered

Build RFC 9562 version-7 UUIDs from a 48-bit millisecond timestamp so lexicographic order matches creation time, then verify compareTo follows the clock.

javaSnippet

Zip Two Lists Pairwise

Zip two lists by index into record pairs: the shorter side caps the length so uneven inputs clip instead of throwing IndexOutOfBounds.

javaSnippet

Class Name Forms For Diagnostics

Compare getName, getSimpleName and getCanonicalName across a plain class, a nested interface, an array and an anonymous class whose canonical name is null.

javaSnippet

CyclicBarrier Broken Barrier Reset

One timed-out await puts a CyclicBarrier into the broken state: later awaiters get BrokenBarrierException immediately, and reset() clears it for the next round.