Files Lines Lazy Large Log Scan
Scan a multi-gigabyte log line by line with Files.lines: lazy streaming, filtered early, and closed by try-with-resources without loading the file.
Page 5 of 7
Scan a multi-gigabyte log line by line with Files.lines: lazy streaming, filtered early, and closed by try-with-resources without loading the file.
Wrap a blocking call in a ManagedBlocker so the common ForkJoinPool spawns compensation threads instead of starving queued parallel work.
Spin up a com.sun.net.httpserver.HttpServer on an ephemeral port, register one handler, and stop it cleanly — no external dependencies.
InheritableThreadLocal copies the parent value at thread construction, so a thread built before the set stays empty and pools never re-copy.
Coordinate two threads with LockSupport.park and unpark: a one-slot permit means unpark before park never blocks, unlike wait/notify ordering.
Expand template tokens with appendReplacement and appendTail: replacements are appended into a StringBuilder while group references stay intact.
Pick the right Matcher entry point: matches demands the whole input, lookingAt anchors the prefix, find scans anywhere for the next hit.
Constrain regex scanning to a slice of a large payload with Matcher.region, so hits outside [regionStart, regionEnd) are never reported.
Stream regex matches as MatchResult objects with Matcher.results, feeding the pipeline directly instead of collecting into a list first.
Stamp API payloads with fixed-offset OffsetDateTime and parse ISO-8601 back, comparing instants instead of strings across offsets.
Handle both branches of an Optional in one call with ifPresentOrElse: the value action and the empty action live side by side, no if-get wrapping.
Build lazy fallbacks with Optional.or: each supplier runs only when the previous chain stage is empty, unlike eager orElse arguments.
Build a tiny lexer with PushbackReader: read one char, classify it, and unread it when the next loop must decide all over again.
Deconstruct records directly in case labels and nest patterns so extraction and validation happen in one exhausted switch.
Discover implementations declared in META-INF/services through java.util.ServiceLoader, iterating lazily instead of hand-wired class name lists.
Flatten each element to zero or more outputs with Stream mapMulti, avoiding the per-element stream allocation that flatMap pays for.
Split structured strings with the two-arg split limit: -1 preserves trailing empty fields that the default split silently drops.
Turn escape sequences that exist as characters into their real control characters with translateEscapes, without regex or manual replacement.
Create platform threads through Thread.ofPlatform with explicit names and an uncaught handler instead of leaving unnamed Thread-N workers behind.
Detect a real monitor deadlock at runtime with findDeadlockedThreads, then report each victim together with the thread holding its lock.
Mirror a folder with Files.walkFileTree: preVisitDirectory creates destinations, visitFile copies files, and visitFileFailed skips unreadable entries.
Store metadata beside objects with WeakHashMap: entries vanish once keys are garbage collected, so caches do not leak strong references.
Arrays.asList gives a fixed-size view: set writes through to the array, add and remove throw; List.of forbids even set; copy into ArrayList to mutate.
Compute in-place cumulative sums with Arrays.parallelPrefix, which applies an associative operator over array prefixes using fork-join parallelism.
Pair a version stamp with compareAndSet so the ABA transition back to the original value cannot fool a stale snapshot into swapping.
Go beyond long with BigInteger: modPow for exponentiation, modInverse for modular inverses, and factorials that overflow primitive types at 21!.
asIntBuffer and friends reinterpret the same bytes through the buffer ByteOrder: big- and little-endian views read different numbers.
Keep secrets in char[] and zero the buffer with Arrays.fill after use; immutable String copies linger until GC, so passwords should never become one.
Classify each char with isLetter, isDigit, and isWhitespace to build a whitelist sanitizer, and use the codePoint variants for astral plane input.
Inject java.time.Clock instead of calling Instant.now() everywhere: fixed clocks return the same instant forever and offset clocks shift the system time.
Filter inside the downstream collector so groups without matches still appear with empty lists, and flatMapping lets one element contribute many values.
Duplicate keys make Collectors.toMap throw IllegalStateException unless a merge function is supplied; a LinkedHashMap factory keeps encounter order.
Collectors.toMap throws NullPointerException when the value mapper returns null; collect into a HashMap by hand or map a default to keep nullable fields.
Render large counts as 15K and 1M with the compact number formatter, switch to LONG style for spelled-out words, and parse the short forms back into numbers.
Implement compareTo with Integer.compare and keep it consistent with equals so TreeSet, Stream.sorted, and sorted collections behave predictably.
Complete a hand-built CompletableFuture from a legacy callback thread so listener APIs join async pipelines; late duplicate callbacks cannot rewrite the result.
Recover a failed async stage with exceptionally, branch success and failure through handle, and observe outcomes with whenComplete without changing the result.
thenApplyAsync pins a stage to an executor; thenApply on an already-completed future runs synchronously on the calling thread, making stage placement explicit.
Initialize per-key values with ConcurrentHashMap.computeIfAbsent, whose contract guarantees the mapping function runs at most once per key under concurrency.
Fan aggregation across the common ForkJoinPool with search for first-match lookup and reduce for merged totals, gated by a parallelism threshold.
Hand tasks between threads with a lock-free ConcurrentLinkedQueue: offer never blocks, poll returns null when drained, and size() is only an O(n) estimate.
ConcurrentSkipListMap keeps keys sorted under concurrent access: ceiling, floor, and subMap range lookups work without external synchronization.
Verify payload integrity with java.util.zip.CRC32: chunked update calls produce the same value as one call, and any single flipped byte shifts the checksum.
Make a class usable in for-each loops by implementing Iterable and returning an Iterator that honors the hasNext/next contract.
Mark background threads as daemons before start: the JVM exits as soon as only daemons remain, without waiting for their loops to finish.
Write ints, shorts, strings, and longs at fixed widths with DataOutputStream, then read them back in the same order with DataInputStream.
The same impossible date resolves three ways: SMART clamps to month end, STRICT rejects outright, LENIENT overflows — pick the policy per input surface.
Format numbers with explicit DecimalFormat patterns: grouping commas, fixed decimals, percent scaling, sign prefixes, and a declared rounding mode.
Wrap an interface implementation with Proxy.newProxyInstance so every method call is recorded first, the same trick frameworks use for auditing.
Model fixed option sets with EnumSet: noneOf, of, range, and complementOf build bit-packed sets of enum constants that iterate in declaration order.
Write equals and hashCode by hand on a plain class so equal objects land in the same HashSet bucket and contains finds them.
invokeAny races the same request across worker tasks, returns the first success, cancels the rest, and throws ExecutionException only when every task fails.
See what a saturated ThreadPoolExecutor does with new tasks: AbortPolicy throws RejectedExecutionException, CallerRunsPolicy runs the task in the submitter.
Try-with-resources manages executor shutdown: ExecutorService.close blocks until every submitted task finishes, replacing the manual shutdown sequence.
Removing from an ArrayList inside for-each trips ConcurrentModificationException; Iterator.remove and removeIf delete through the cursor safely.
Append to a log through FileChannel and call force(true) so data and metadata reach the device before the caller returns, surviving a process crash.
FileChannel.read into a ByteBuffer array scatters bytes across buffers in order, letting one call fill a length field and its payload without copying.
transferTo hands bytes between channels without a user-space buffer; a call may move fewer bytes than requested, so the loop advances by the returned count.
Search a directory tree lazily with Files.find, pairing a glob PathMatcher with file attributes and a depth cap instead of walking every node.
Fetch size, type, and timestamps in one Files.readAttributes call so upload probes avoid several separate filesystem stat round trips.
Control Files.writeString with CREATE_NEW, CREATE, APPEND, and TRUNCATE_EXISTING so overwrites, appends, and fail-on-existing behavior stay explicit.
Read total, unallocated, and usable space from the volume holding the working directory so a disk-full condition becomes a planned degradation.
Order function application deliberately: compose runs its argument first, andThen runs it second, and chaining both builds a normalization pipeline.
cancel(true) sends an interrupt to a running Future's worker thread and marks the task cancelled, after which get() throws CancellationException forever.
Read configuration from System.getenv with explicit fallbacks, because getenv returns null for missing variables and the map itself is read-only.
Compress bytes with GZIPOutputStream and read them back with GZIPInputStream, verifying a byte-exact roundtrip and the failure path for non-gzip input.
Compute union, intersection, and difference over HashSet with addAll, retainAll, and removeAll so tag comparisons run without hand-written loops.
Format bytes as delimited hexadecimal and parse them back with HexFormat; uppercase, prefix, and separator are configurable and bad input fails fast.
Sign a payload with the JCA Mac under HmacSHA256 and verify by recomputing the tag through HexFormat; any changed byte flips the tag and fails the comparison.
Store keys by reference instead of equals: two distinct String instances with the same characters occupy two entries in an IdentityHashMap.
Bind matched values directly with instanceof type patterns: the variable is in scope in the same condition and flows through null-safe checks.
Measure with Instant and Duration: capture the start, compare elapsed against a budget with compareTo, and report toMillis instead of hand-rolled math.
Use bitCount, rotateLeft, highestOneBit, and lowestOneBit for popcount, circular shifts, and power-of-two rounding without manual loops.
Autoboxed values from -128 to 127 are cached, so == compares the same object inside the range but distinct objects once boxing exceeds it.
When two interfaces supply the same default method, the implementing class must override it and pick a side with InterfaceName.super.method().
Generate numeric pipelines with IntStream.range and iterate, mixing primitive sum with boxed collectors and index-based array access in one pass.
Write a manifest into a jar with JarOutputStream and read its attributes back with JarFile, the metadata version reporting relies on.
Wrap an expensive initializer in a memoized Supplier so the value is computed on first get and reused afterwards without re-running the loader.
Hand items to a consumer with LinkedTransferQueue transfer, which blocks until the item is taken, while tryTransfer fails fast when nobody waits.
Deduplicate while keeping first-seen order: HashSet scrambles iteration, LinkedHashSet remembers insertion, and re-adding an element never moves it.
Split a list into fixed-size batches with subList windows so bulk calls respect API limits; each batch is a read-only view of the backing list.
Match an Accept-Language header against supported locales: Locale.filter returns all matches, Locale.lookup picks the single best one by weight.
Parse BCP 47 tags into Locale objects with forLanguageTag, build canonical tags back with Locale.Builder, and watch ill-formed tags resolve to und.
Turkish uppercases i to dotted İ: use Locale.ROOT or equalsIgnoreCase for keys and protocol tokens, never the machine default locale.
Map.copyOf and Set.copyOf freeze a snapshot, while Collections.unmodifiableMap stays a live view that tracks the source, and both reject every write.
Map a file into memory with FileChannel.map and read it as a MappedByteBuffer, so large files are scanned without copying through heap buffers.
User-supplied replacement text containing $ or backslash throws in replaceAll; Matcher.quoteReplacement escapes both so substitution stays literal.
Build replacement text from a MatchResult inside the function form of replaceAll, so dollar signs in untrusted input can never trigger template expansion.
Catch integer overflow when it happens: addExact, multiplyExact, negateExact, and toIntExact throw ArithmeticException instead of wrapping silently.
Clamp values into a range with the Java 21 Math.clamp overloads: long-to-int narrowing never overflows, and min greater than max is rejected outright.
Tell truncating division and floor division apart: % keeps the dividend sign while Math.floorMod always lands in 0..divisor-1, ideal for circular indexing.
Build user-facing messages with MessageFormat placeholders so numbers and dates render per Locale, and single quotes need doubling to stay literal.
parse() silently ignores trailing garbage; the ParsePosition overload returns null on failure and exposes getIndex and getErrorIndex so bad input is rejected.
Attach an ObjectInputFilter allowlist before readObject so only approved classes are rebuilt; anything else fails fast as InvalidClassException.
Give nullable values explicit fallbacks with requireNonNullElse, requireNonNullElseGet, and Objects.toString so the default is stated at the call site.
orElse evaluates its argument even on a cache hit, while orElseGet invokes the supplier only when the Optional is empty.
parallelStream splits work across the common pool: forEach drops encounter order, forEachOrdered restores it, while sum and findFirst stay deterministic.
Parse CLI numbers defensively: wrap parseInt in try/catch, reject blanks and out-of-range ports, and return OptionalInt instead of leaking exceptions.
Derive the relative path between two locations with relativize and anchor it back with resolve; mixing absolute and relative inputs throws.
Wrap untrusted strings with Pattern.quote before compiling so regex metacharacters match literally instead of throwing or widening the match.