Bridge Streams And Channels With Channels
Wrap InputStream and OutputStream as channels with java.nio.channels.Channels, then copy bytes through a shared ByteBuffer.
Page 21 of 50
Wrap InputStream and OutputStream as channels with java.nio.channels.Channels, then copy bytes through a shared ByteBuffer.
Register a cleanup action with java.lang.ref.Cleaner, call Cleanable.clean explicitly, and show that repeat calls stay idempotent.
Rotate, reverse, shuffle, and count frequencies in lists with the Collections utilities while keeping seeded shuffles reproducible.
Concatenate stream elements with Collectors.joining, adding delimiters, prefixes, suffixes, and mapping each element to text in one terminal operation.
Fold stream elements with Collectors.reducing in its identity, mapped, and Optional forms, including an empty-stream fallback.
Sort records whose keys may be null by wrapping inner comparators with nullsFirst or nullsLast, keeping null handling out of business code.
Select currencies by ISO code or locale, then format amounts with the right symbol, grouping, and default fraction digits.
Send and receive UDP datagrams through DatagramChannel over loopback, showing connectionless addressing and byte buffer reuse.
Compress payloads with Deflater and restore them with Inflater, checking byte counts, zlib headers, and a lossless round trip.
Build a lazy thread-safe singleton with volatile and double-checked locking, where the second check inside the synchronized block prevents duplicate builds.
Accumulate double samples with DoubleAdder, read sumThenReset, and compare the running total with doubleValue after many adds.
Derive a shared secret with javax.crypto.KeyAgreement over EC keys and verify that both sides compute identical bytes.
Generate an EC key pair, sign a message with SHA256withECDSA, and verify it with the public key while rejecting a tampered payload.
Unwrap checked failures from concurrent tasks with ExecutionException.getCause, restoring the original exception instead of wrapping it in another layer.
Take over serialization with Externalizable, writing only the fields you choose in writeExternal and restoring them in readExternal.
Read and write whole text files in one call with Files.readString and writeString, choosing UTF-8 explicitly for predictable encoding.
Create a per-run scratch directory with Files.createTempDirectory, write working files inside it, and clean everything up recursively on shutdown.
Use Stream gather with Gatherers.scan to emit a running total after every element, including a custom String prefix accumulator.
Parse Set-Cookie style headers with HttpCookie.parse, read attributes, then rebuild a Cookie request header from a small jar.
Read a small payload into memory with readAllBytes, then stream it between streams with transferTo instead of hand-rolled buffer loops.
Store a generated AES key in a PKCS12 KeyStore, write it to disk, reload it with the same password, and compare key material.
Read text with LineNumberReader, set line numbers before parsing, and use mark and reset to reparse a section with correct numbering.
Generate a date stream with LocalDate datesUntil, step it by weeks, and confirm the end date is excluded from the result.
Aggregate a concurrent maximum with LongAccumulator while a LongAdder collects totals, then reset both without locking.
Carry key-value pairs through pipelines with the immutable Map.entry factory, whose instances reject setValue and slot into collectors without a map.
Control BigDecimal division precision with MathContext and rounding modes so non-terminating results never throw unexpectedly.
Inspect heap and non-heap memory through MemoryMXBean, printing used, committed, and maximum bytes around an allocation.
Look up virtual and static methods with MethodHandles, adapt signatures, and bind arguments before invoking them with invokeExact.
Encode with Base64.getMimeEncoder so long payloads wrap at a fixed width, then decode the wrapped text back to the original bytes.
Enumerate NetworkInterface instances, read hardware addresses and MTU, and filter usable IPv4 addresses excluding loopback.
Format a number with a locale and parse the result back through the same locale, so the roundtrip restores the value and mismatched locales truncate it.
Insert Thread.onSpinWait into a bounded spin loop so the CPU gets a hint that the thread is waiting on a flag rather than doing work.
Read host details from the OperatingSystemMXBean: name, arch, processors, and a load average that may be unavailable as -1.
Flatten a list of Optional values with Optional.stream so empty slots vanish from the pipeline without any explicit isPresent check.
Derive password hashes with PBKDF2WithHmacSHA256, a per-user random salt, and a high iteration count, then compare digests in constant time.
Use java.time.Period for calendar-based spans across months and years, where adding two months means something different every time.
Move bytes between threads through a NIO Pipe, using a dedicated writer thread and an EOF read loop instead of a shared buffer.
Seek to fixed offsets in a RandomAccessFile to read records, append at the end, and overwrite fields in place.
Inspect a record through getRecordComponents, invoke each accessor reflectively, and sum the values returned by the components.
Create and read arrays of unknown component type through java.lang.reflect.Array, including primitive arrays and type-checked writes.
Concatenate streams with SequenceInputStream, first as a pair and then through an enumeration, and read the joined bytes in order.
Accept one loopback client with ServerSocket, echo a line back through the socket streams, and close both ends with try-with-resources.
Register JVM shutdown hooks with Runtime.addShutdownHook, verify they can be removed, and use them for final flush or cleanup on normal exit.
Generate reproducible random sequences with SplittableRandom and split independent child generators for parallel tasks.
Join two streams with Stream.concat, then confirm the result stays lazy by counting side effects before the terminal operation runs.
Create bounded sequences with Stream.generate plus limit, and verify that no supplier call happens before a terminal operation.
Split text with StringTokenizer, including the returnDelims mode that keeps separators as tokens, and contrast it with String.split.
Wrap a list with Collections.synchronizedList, iterate under an explicit lock, and contrast it with an unsynchronized ArrayList.
Query sorted TreeSet subsets with headSet, tailSet, and subSet, then find floor, ceiling, and polled extremes in log time.
Read URI components, resolve relative references, and normalize dot segments without string concatenation or manual path parsing.
Derive a version 3 UUID with nameUUIDFromBytes, check its version and variant, and contrast it with a random version 4 UUID.
Write two entries with ZipOutputStream, then stream them back through ZipInputStream and read each entry before advancing.
Cancel stale requests with AbortController so a fast typist does not let an older response overwrite the newest one.
Move an ArrayBuffer into a larger buffer with transfer, confirm the source detaches, and inspect the zero-filled tail.
Compress and decompress strings with CompressionStream and DecompressionStream, piping through Blob so no third-party codec is needed.
Hash UTF-8 text with crypto.subtle.digest, convert the digest to hex, compare repeated and case-changed inputs, and check the fixed length.
Register a custom element and use connectedCallback and attributeChangedCallback to render content and react to attribute updates.
Build timestamps with Date.UTC so month math and comparisons stay independent of the machine time zone, then format and parse them.
Define getter and setter descriptors with Object.defineProperty to validate writes and expose computed values without leaking internals.
Register cleanup with DisposableStack defer, use, and adopt, then dispose once and watch callbacks run in reverse order.
Build a tiny pub/sub with EventTarget and CustomEvent so modules communicate through real events instead of ad-hoc callbacks.
Open an IndexedDB database, write records in one transaction, and read them back by key with a small promise wrapper around events.
Render dates for a locale and turn instants into relative phrases with Intl.DateTimeFormat and RelativeTimeFormat.
Normalize and deduplicate BCP 47 tags with Intl.getCanonicalLocales, catch invalid tags, and feed the result to a formatter.
Use Intl.Locale maximize and minimize to resolve likely subtags, then attach calendar and numbering options to the tag.
Format measurements with Intl.NumberFormat unit style, switch display modes, and use formatToParts to separate the number from its unit.
List calendars, units, currencies, and time zones with Intl.supportedValuesOf, then feed a supported unit into NumberFormat.
Implement Symbol.iterator so your own objects work with for-of, spread, and destructuring — the same protocol as built-in collections.
Group records with Map.groupBy using object keys, compare identity with a structural clone, and contrast the result with Object.groupBy string keys.
Traverse possibly-missing data with optional chaining and fall back with nullish coalescing so falsy values are not clobbered.
Collect every outcome with Promise.allSettled when a batch must not fail as a whole, then branch on fulfilled versus rejected.
Intercept writes with a Proxy set trap so invalid assignments fail loudly at the mutation site instead of corrupting state silently.
Batch many rapid updates into one flush by scheduling work on the microtask queue so renders and network calls stay coalesced.
Adapt a sync generator into a web ReadableStream with ReadableStream.from, then consume it with async iteration.
Branch one ReadableStream into two independent readers with tee, then drain both branches concurrently.
Call Reflect.construct with a different newTarget to borrow a constructor while producing an instance of a subclass prototype.
Enable the d flag on regular expressions so every match exposes start and end indices for the whole pattern and each capture group.
Use the RegExp v flag to subtract and intersect Unicode character sets, combine script properties, and validate identifiers with set notation.
Create a Request from a URL and options, clone it before reading the body, and inspect method, headers, and cache mode without sending traffic.
Clone a Response before reading its body so one consumer parses JSON while another reads text, and observe what happens on re-read.
Build Windows paths and regex patterns with String.raw tagged templates, comparing raw backslashes against normal escapes.
Clone nested data with structuredClone instead of JSON round-trips — Dates, Maps, Sets, and cycles survive the copy intact.
Override Symbol.hasInstance to accept plain objects by shape, then filter mixed samples through the custom instanceof check.
Use toSpliced to insert, remove, and replace array elements while returning a new array, leaving the original list untouched.
Match Greek script, numbers, letters, and pictographs with Unicode property escapes, including the required u flag.
Validate absolute and relative URLs with URL.parse, return null instead of throwing, and read host, port, and query values.
Compose URLs with the URL API and searchParams so encoding, duplicate keys, and relative bases are handled by the platform.
Serialize work across tabs with navigator.locks.request, so two tabs never write the same storage key at the same moment.
Build a WritableStream with write, close, and abort handlers, pipe a ReadableStream into it, and collect the transformed chunks.
AbortSignal.any fires when the first source aborts and adopts its reason, so a request can honor both a deadline and a user-initiated stop from one signal.
toSorted, toReversed, toSpliced and with return new arrays and leave the source intact, replacing the mutate-then-clone pattern around shared state.
Splitting argv into booleans flags, --key=value pairs and positionals, with -- ending option parsing, covers most CLIs before reaching for a parser library.
Every control posts as a string, but number and range inputs expose valueAsNumber, checkboxes carry a value attribute, and validity maps failed rules.
A rejection skips every then until one catch; handlers after the catch resume normally, and finally runs on both paths without changing the settled value.
A deque as a sliding window evicts timestamps older than the horizon in one amortized pass, so counting pings in the last N seconds stays O(1) per call.
struct.pack and unpack move values into fixed-layout byte strings; iter_unpack walks a buffer without slicing, and wrong sizes raise struct.error.
Structure a CLI with argparse subparsers so each verb owns its flags and help text, and the top level stays a clean verb list.
Parse Python source with ast, insert a trace call with NodeTransformer, and unparse the rewritten tree back to valid source.
Bound concurrent coroutines with a semaphore inside gather so a large batch does not open every connection at once.
Move blocking work off the event loop with asyncio.to_thread so synchronous checks run in worker threads while other coroutines continue.