CheckedInputStream With Adler32 Checksum
Compute and verify rolling Adler32 checksums in-flight with CheckedOutputStream and CheckedInputStream, catching single-bit stream tampering.
Compute and verify rolling Adler32 checksums in-flight with CheckedOutputStream and CheckedInputStream, catching single-bit stream tampering.
Normalize trailing zeros with BigDecimal.stripTrailingZeros and print plain numbers via toPlainString so powers of ten never show 1E+2.
Toggle half-open slot ranges in BitSet with set(from, to), flip(from, to), and clear(from, to), then test schedule overlap via intersects.
Block with take() for the first queued item, then coalesce all ready elements via drainTo in one consumer pass instead of spinning or polling.
Share buffer bytes across independent cursors with duplicate() and hand untrusted callers immutable views via asReadOnlyBuffer() safely.
Flip a ByteBuffer after writing and carve independent sub-views with slice() and slice(index, length) that share bytes without moving parent positions.
Inspect sealed interfaces at runtime with Class.isSealed() and getPermittedSubclasses() to build a closed allowlist before reflection dispatch.
Cache per-Class reflection metadata lazily with java.lang.ClassValue, avoiding ClassLoader leaks while supporting explicit invalidation via remove.
CompletableFuture.anyOf settles on the first completed stage even if it failed, so wrap noisy mirrors with exceptionally before racing them.
Keep ConcurrentHashMap clean when computeIfAbsent returns null or throws: failed loads leave the key absent so a subsequent retry can succeed.
Query live sorted subSet ranges and atomic pollFirst entries on ConcurrentSkipListSet while concurrent mutations iterate safely without locks.
Deduplicate event handlers with CopyOnWriteArraySet and iterate over a point-in-time snapshot so listeners can unsubscribe mid-dispatch safely.
Coordinate concurrent workers with two CountDownLatch gates: a one-count start gun to launch together and a worker-count latch to await finish.
Use the arrival index returned by CyclicBarrier.await to elect one thread per round without extra locks, then reuse the barrier across phases.
Enable setParseBigDecimal(true) on DecimalFormat with ParsePosition checks so long grouped decimals parse without Double rounding or tail junk.
Swap reusable list buffers between producer and consumer with Exchanger, and enforce a bounded wait using timed exchange with TimeoutException.
Pass maxDepth to Files.walk to stop at 0, 1, or N directory levels, keeping deep subdirectories unread while closing the stream via try-with-resources.
Implement java.util.Formattable so a custom type honors alternate #, precision .N, left-justify -, width, and uppercase %S flags in String.format.
Inject JDK 17 InstantSource instead of Clock when code only needs UTC instants, composing fixed, offset, and tick wrappers plus withZone adapters.
Switch regex patterns mid-scan with Matcher.usePattern and enable useTransparentBounds so lookaheads inspect characters past regionEnd.
Convert internationalized domain names between Unicode and ASCII Punycode via java.net.IDN, enforcing STD3 rules to reject unsafe host characters.
Compare arbitrary Object references holding primitive arrays, nested Object[] graphs, and nulls safely using Objects.deepEquals instead of ==.
Override Phaser.onAdvance to summarize each completed phase and return true once the final stage finishes, cleanly marking the phaser terminated.
Stream structured regex matches from a Scanner with findAll(Pattern), extracting capture groups and byte offsets from MatchResult lazily.
Acquire multiple Semaphore permits at once for heavy tasks, then call drainPermits to seize remaining capacity before releasing them back.
Split text with JDK 21 String.splitWithDelimiters so matched separators stay in odd array slots, comparing positive, zero, and negative limit rules.
Query LocalDate.range(ChronoField.DAY_OF_MONTH) to inspect month-specific ValueRange bounds and validate candidate days before construction.
Read and write multi-byte integers in a byte[] buffer using byteArrayViewVarHandle with explicit ByteOrder and aligned atomic CAS checks.
Derive monthly billing windows from YearMonth.now(Clock.fixed) so leap-year February and 31-day rollovers behave deterministically in tests.
Consume a two-ended work queue with ArrayDeque pollFirst and pollLast, pairing entries from both sides until the deque runs empty.
Accept CharSequence at API boundaries so String, StringBuilder, and StringBuffer all pass through without intermediate toString copies.
Stream a string as int code points with String.codePoints, so per-character logic counts one emoji as a single value instead of two surrogate units.
Decide whether two collections share nothing with Collections.disjoint, one call instead of nested loops, with an empty collection always reporting true.
Create a missing directory tree with Files.createDirectories, which succeeds silently when the directory exists instead of throwing like createDirectory.
Read the weekday of a LocalDate with getDayOfWeek, test SATURDAY and SUNDAY for weekend logic, and roll forward with TemporalAdjusters.next.
Scale spans with Duration.dividedBy, count whole occurrences of a sub-span, and flip signs with negated and abs — zero divisor throws, not yields infinity.
Split a Duration into day, hour, minute, and second parts with toXxxPart methods, where each part is a remainder and toHours is the total.
Read an enum constant position with ordinal() and valueOf(), and see why declaration order, not source order of use, decides every ordinal value.
Find where a smaller list appears inside a larger one with Collections.indexOfSubList, matching consecutive element runs rather than single items like indexOf.
Advance dates with plusDays and minusDays across month boundaries, then convert with toEpochDay and fromEpochDay when plain day counts are needed.
List the ISO country and language codes the JDK knows with getISOCountries and getISOLanguages, then validate user input against those sets.
Render dates with ofLocalizedDate and FormatStyle, where the pattern itself comes from the formatter locale and FULL/LONG need a zone on the temporal.
Roll up grouped long metrics with Collectors.summarizingLong and LongSummaryStatistics, keeping count, sum, min, and max together per group.
Write conditionally into a Map with putIfAbsent and computeIfPresent, so a first writer wins a slot and later writers adjust existing entries.
Carry a time-of-day with a fixed UTC offset in OffsetTime, keeping wall-clock through withOffsetSameLocal and the instant through withOffsetSameInstant.
Transform wrapped values with map and keep the Optional flat with flatMap, so parsing and validation steps compose without nested wrappers.
Treat 32-bit patterns above Integer.MAX_VALUE as large positives with parseUnsignedInt and divideUnsigned, matching what wire formats and hashes encode.
Read ofPattern letter counts: M counts switch number to short, full, narrow text; yy parses with a 2000-2099 base; y is year-of-era while u is the year.
Parse P1Y2M3W4D text where weeks fold into days, add periods component-wise with no normalization, and normalize only when months should carry into years.
InputStream.readNBytes reads up to the requested count and never returns negative values, so chunked uploads get a clean empty-array end signal.
Insert at both ends with addFirst and addLast from the JDK 21 SequencedCollection interface, then poll from either side without index arithmetic.
flatMap expands each stream element into a sub-stream, generating ordered pair combinations or flattening nested lists in one pipeline.
String.compareTo compares UTF-16 code units one position at a time, so uppercase letters sort before lowercase and prefixes yield a length difference.
Bytes store -128..127, so anything above 127 wraps negative; & 0xFF widens to an unsigned int for CRC, hashing, and wire-format work.
Implement a custom Collector whose combiner folds two Welford accumulators, so parallel streams land on the same sample variance as the sequential run.
Accept month names in any letter case by building a DateTimeFormatter with parseCaseInsensitive instead of upper-casing the input yourself first.
Flip Windows hidden and read-only flags on a file through DosFileAttributeView, then prove the read-only attribute rejects rewrites until you clear it.
Group files from a directory walk by a size-plus-SHA-256 fingerprint so only true byte-level duplicates survive the grouping.
Tier.values() hands back a new array on every call, so callers mutate their own copy while the shared constant list stays intact; cache it for hot paths.
Vector.elements() returns an Enumeration; asIterator and Collections.list bridge it into for-each and the Stream API without rewriting legacy code.
Files.list and Files.walk return DirectoryStream-backed streams that terminal ops never close; wrap every walk in try-with-resources or leak handles.
A blocked channel read on a socket responds to interrupt by closing the channel and raising ClosedByInterruptException instead of returning.
find() resumes at the previous match end, so overlapping hits are invisible; restarting find from start+1 reveals every occurrence.
The default percent instance rounds to whole percents; setMaximumFractionDigits restores decimals and parse turns 43.21% back into the ratio 0.4321.
One call site with long, Integer, and int... overloads shows resolution order: widening beats boxing beats varargs, so pick(1) lands on long.
One getPathMatcher call serves both syntaxes: glob: patterns cross directories with ** while regex: matches paths with a plain regular expression.
Poll new entries into a bounded min-heap of size k: overflow evicts the smallest survivor, and a final sort turns the heap into a ranked list.
ProcessBuilder.environment() inherits the parent environment and accepts overrides, so a child process receives staged config without editing global state.
A compact constructor takes defensive copies of mutable fields, so later caller mutations never leak into the record and accessors hand out immutable lists.
Encrypt and decrypt payloads with RSA-OAEP via Cipher, passing an explicit OAEPParameterSpec so the digest and MGF1 hash never depend on provider defaults.
Count character frequencies and sum -p log2 p to score repeat-heavy strings near zero bits per character — a rough signal, not a security verdict.
shutdownOutput closes only the write direction: the peer sees a clean EOF, finishes its read loop, and can still send its final reply back.
Show that an instance monitor never blocks the class monitor: code holding one object lock runs while the static critical section proceeds concurrently.
Strip ANSI escape sequences from colored CLI output with one regex covering CSI, OSC, and two-byte controls, leaving plain text untouched.
Derive HOTP and TOTP one-time codes from HMAC-SHA1 with dynamic truncation, checking the published RFC 4226 and RFC 6238 test vectors end to end.
Bound virtual thread concurrency with a Semaphore: tasks fan out cheaply while the permit count caps simultaneous in-flight downstream calls.
Cap ZipInputStream entries with a streaming byte budget: declared sizes can be unknown, so count every read and abort the moment an entry overshoots.
Emit ANSI SGR escape sequences to color terminal output, then strip every sequence with a regex so piped or CI output stays clean.
Extend AbstractQueuedSynchronizer with tryAcquireShared and tryReleaseShared to rebuild a countdown latch from the shared queue primitives.
Assign a String[] to an Object[] alias and store an Integer to trigger ArrayStoreException at runtime while the original array stays intact.
Primitive arrays sort ascending only; reversing or field-based ordering means boxing to Integer[] and passing a Comparator to Arrays.sort.
Run one echo roundtrip over AsynchronousSocketChannel completion handlers while the main thread parks on a CountDownLatch until callbacks land.
Capture produced bytes in a ByteArrayOutputStream, replay them through a ByteArrayInputStream, and reuse the same buffer after reset without reallocating.
Character.digit maps a char to its value under a radix and forDigit goes back; invalid digits return -1 instead of throwing.
Character.getName reports the official Unicode name of any code point, or null for unassigned ones, ideal for debugging odd glyphs.
Fill a CharBuffer with put, flip to drain with get, and compact to keep unread chars for the next write instead of clearing them away.
Charset.forName accepts case-insensitive aliases while each charset keeps one canonical name; availableCharsets lists every registered charset.
Wrap a failing dependency in a breaker: consecutive failures trip it to OPEN and later calls fast-fail instead of hammering a dead upstream.
Prefer a copy constructor over clone(): a shallow clone shares mutable list state, while an explicit constructor copies fields deliberately.
Build each CollationKey once and sort by keys, then compare repeatedly without paying Collator.compare on every lookup during large sorts.
Return null from a ConcurrentHashMap remapping function to remove the entry, keep absent keys absent, and replace existing values in place.
addFirst and pollLast drain a ConcurrentLinkedDeque from opposite ends without coordination; size() walks the chain and iterators stay weakly consistent.
System.console() may be null when the program runs without a terminal; guard it, prompt with readLine, and take secrets as char arrays from readPassword.
Split an array into forked leaves, fold child results in onCompletion, and read the grand total back through getRawResult after invoke.
CRC32C update() calls accumulate the same checksum whether input arrives whole or chunked, and flipping one byte changes the value, exposing corruption.
Encode one CSV field per RFC 4180: quote when the value holds a comma, quote, or line break, and double embedded quotes when escaping.
user.dir anchors relative paths for the whole JVM: Paths.get("").toAbsolutePath() lands on the same directory that System.getProperty("user.dir") reports.
Check whether two inclusive date ranges overlap with a two-comparison rule covering containment, adjacency, and disjoint spans.
parseBest tries queries from most to least complete: an optional-section formatter parses timestamps, datetimes, and date-only strings without try/catch chains.
Pattern letter B formats the finer day period — morning, afternoon, evening, night — where am/pm collapses the whole day into two halves.