Future State Non Blocking Polling
Read a Future's terminal state non-blockingly with state() and the State enum, distinguishing SUCCESS, FAILED, CANCELLED, and RUNNING without waiting.
Page 3 of 7
Read a Future's terminal state non-blockingly with state() and the State enum, distinguishing SUCCESS, FAILED, CANCELLED, and RUNNING without waiting.
Run stream mapping on up to N virtual threads with Gatherers.mapConcurrent, which fans work out concurrently yet keeps encounter order in the output.
Aggregate parallel streams straight into ConcurrentMaps with groupingByConcurrent and toConcurrentMap, supplying the merge function key conflicts require.
Allocate maps and sets sized for a known entry count with HashMap.newHashMap and HashSet.newHashSet so later puts generally add without resizing.
Format byte counts through a binary-unit ladder from B to TiB with one-decimal rounding, so reports show 1.5 GiB instead of raw long values.
Bucket a date into fiscal quarters with IsoFields: QUARTER_OF_YEAR labels the quarter and DAY_OF_QUARTER reconstructs its first and last day.
Feed urgent jobs from the head and routine jobs from the tail of a bounded LinkedBlockingDeque; timed offerLast degrades instead of blocking forever.
Convert a List with toArray: the no-arg form erases to Object[], new String[0] allocates the right type, and an oversized array keeps spare slots null.
Scan column by column to keep only the characters every string shares, so grouped keys like deploy-api and deploy-web reduce to their deploy- stem.
Math.abs(Integer.MIN_VALUE) does not throw: the documented contract returns the same negative value, so widen to long or guard the boundary before negating.
Page counts without off-by-one: Math.ceilDiv rounds the quotient up and rejects zero divisors; unsignedMultiplyHigh returns the 128-bit product's top half.
Math.fma computes a*b+c with unlimited intermediate precision and rounds once, so it can differ from the two-rounding expression a*b+c in the last bits.
Step between representable doubles with Math.nextUp and nextDown, measure the gap with ulp, and watch nextUp of MAX_VALUE reach Infinity.
One multi-catch clause handles NumberFormatException and DateTimeParseException together; the types must be unrelated or the compiler rejects it.
An inner class carries an outer instance and reads its private fields; a static nested class is a plain top-level class parked inside another one.
Process.onExit returns a CompletableFuture completed at termination regardless of exit status, so cleanup code can chain instead of blocking on waitFor.
Refresh under a write lock, then take the read lock before releasing the write lock — the documented downgrade that keeps writers out with no unlocked gap.
Break a version string apart with Runtime.Version.parse: feature, interim, update and patch come back as ints while pre, build and optional arrive as Optionals.
Request a DRBG SecureRandom at 256-bit strength with prediction resistance and reseeding, then read back the algorithm, provider and a HexFormat token.
Seek a SeekableByteChannel to any byte offset, read or overwrite in place, and watch the same channel re-read after rewinding its position.
Format dates safely across threads: SimpleDateFormat instances are not synchronized per javadoc, so build one per call or share an immutable DateTimeFormatter.
Route printStackTrace into a StringWriter and PrintWriter to capture the whole trace as one string for log lines, assertions, and error envelopes.
After an optimistic snapshot fails validation, take a read lock and let tryConvertToWriteLock upgrade it to a write stamp in one uncontended step.
Break a log-style line into word, number, quoted phrase and raw character tokens with StreamTokenizer, and report line ends via lineno once enabled.
StrictMath pins transcendental functions to published fdlibm 5.3 algorithms so results are bit-for-bit identical on every platform; Math trades that for speed.
String literals share one pooled instance, a new copy is equal but not identical, and intern() returns the canonical pooled instance for the same content.
String.transform applies a function to the string and returns its result, so multi-step text pipelines read in order without nested call nesting.
Race the same append loop on a shared StringBuffer and StringBuilder: the synchronized buffer lands every char, the unsynchronized one prints its shortfall.
System.arraycopy copies between arrays with overlap handled as if through a temporary buffer, and throws instead of writing when bounds or types do not fit.
Thread.sleep(Duration) sleeps a JDK-19 style span: negative durations are a silent no-op, and interruption throws InterruptedException after clearing the flag.
Subclass ThreadPoolExecutor to time every task: beforeExecute stamps the start, afterExecute reports elapsed time and whether the task ended with a throwable.
Checked IOException cannot cross a stream lambda; wrap it in UncheckedIOException at the boundary and unwrap the cause where the consumer handles it.
compareAndExchange returns the witness value: the expected value on success, but on failure the actual current value, which boolean CAS cannot reveal.
Compare nested arrays with Arrays.deepEquals and print them with deepToString, because equals and toString stop at the outer array reference.
Break a paragraph into directional runs with java.text.Bidi so renders can lay out LTR and RTL segments with correct bounds.
BreakIterator.getLineInstance exposes legal wrap positions at word boundaries so greedy wrapping never splits a word mid-line.
Heap buffers expose a backing array while direct buffers throw from array(), yet both share identical get/put APIs for the same byte-level reads.
Choose between REPORT and REPLACE on CharsetEncoder so unmappable characters either stop the encode with an exception or become a placeholder byte.
Walk a ConcurrentHashMap with forEach entry actions and keySet views, relying on weakly consistent iteration instead of snapshots.
RemoveIf deletes every element matching a predicate in one pass and reports whether anything changed, unlike manual iterator removal loops.
Merge two independent futures with thenCombine: the callback fires only once both stages complete, then ordinary thenApply chains continue downstream.
Observe the outcome of async work with whenComplete: the callback sees the success value or the failure exception without altering either path.
A custom Gatherer with ofSequential and Integrator.ofGreedy collapses consecutive repeats, showing state, downstream.push, and the boolean contract.
Confirm that Charset.defaultCharset is UTF-8 since JDK 18 regardless of platform, so charset-less getBytes and new String behave identically everywhere.
Call shutdownNow on a busy single-thread executor to interrupt the running task and drain the queue: it returns the runnables that never commenced.
Truncate a file in place with FileChannel.truncate, which only takes effect below the current size and is a documented no-op at or above it.
Files.createDirectory throws NoSuchFileException when a parent is missing, while createDirectories fills each level and is safe to call twice.
exists() and notExists() are both false when accessibility is unknown, so pair them to distinguish definitely missing from cannot tell.
Split a ForkJoinTask at a sequential threshold with invokeAll so the work-stealing pool stops forking once segments are small enough.
Bucket instants with truncatedTo for exact-duration units, fall back to epoch-second arithmetic for 15-minute windows, and learn where MONTHS throws.
JapaneseDate and ThaiBuddhistDate express the same LocalDate in era-based calendars, and convert straight back through getChronology.
Compose multi-key ordering with two sorts: pass one orders the tiebreak key, pass two sorts by the primary, and stable TimSort keeps that tiebreak order.
Declare a record inside a method to model intermediate results with methods and sorting, without widening the class-level API surface.
Sort map entries by value with Map.Entry.comparingByValue, then chain thenComparing(comparingByKey) so tied values keep a stable order.
Putting into a HashMap while iterating throws ConcurrentModificationException, while ConcurrentHashMap iterates weakly consistent without failing.
Distinguish "no match" from "not enough input yet" with hitEnd so streaming validators can wait for more data instead of rejecting early.
Show that Math.round sends ties toward positive infinity while RoundingMode.HALF_UP rounds away from zero, so -2.5 lands on -2 versus -3.
Compare MACs and hashes with MessageDigest.isEqual, whose constant-time scan avoids the early-exit leak that Arrays.equals has.
MonthDay.of(2, 29) maps to Feb 29 on leap years and Feb 28 otherwise, so recurring annual dates survive the calendar edge case.
Open a temp file channel with StandardOpenOption.DELETE_ON_CLOSE so the scratch file disappears when the channel closes, even on failure paths.
One thread watches accept and read readiness for many sockets with Selector and SelectionKey, including the manual selectedKeys removal loop.
startsWith and endsWith on Path compare whole path elements instead of characters, which keeps route matching honest when names share prefixes.
Persist small settings with the Preferences API: type-aware putters, safe getters with defaults, and an explicit flush to force the backing store.
Construct ReentrantLock(true) so blocked workers are granted the lock in arrival order instead of letting later threads barge ahead.
lockInterruptibly lets a blocked waiter be cancelled by interrupt, unlike lock(), so stuck lock waits cannot pin threads forever.
regionMatches compares character regions with an offset and an ignoreCase flag, giving allocation-free case-insensitive prefix and infix checks.
A monotonic deque keeps window candidates ordered so each index enters and leaves at most once, streaming maxima for sensors and rate windows.
Walk an XML document with the StAX XMLStreamReader cursor, dispatching on START_ELEMENT, CHARACTERS, and END_ELEMENT events as you pull them.
Deduplicate a stream by a chosen key with a seen-set filter, since distinct() only compares whole records by equals.
Slide a fixed-size window across a stream with Gatherers.windowSliding so every adjacent pair shares a window, unlike windowFixed non-overlapping batches.
Feed possibly-null values through Stream.ofNullable and flatMap so nulls vanish at the source instead of triggering NPE mid-pipeline.
Turn a string into an IntStream of chars, sort it, and compare signatures so anagram detection stays allocation-light on primitive streams.
Aa and BB share hashCode 2112 yet stay two entries in a HashMap, showing why equals must back every hash-based lookup.
String.replace treats the target as literal text while replaceAll compiles a regex, so a plain dot replaces itself or swallows every character.
Tell the two interrupt probes apart: static Thread.interrupted reads and clears the flag, instance isInterrupted only reads, and blocking calls clear it too.
Calling run() directly stays on the current thread; only start() creates a worker thread, shown by printing each execution thread name.
Classify characters with Character.UnicodeBlock so a validator can reject unexpected scripts instead of matching ad-hoc code point ranges.
Character.isDigit accepts every Unicode decimal digit while regex \d stays ASCII-only until UNICODE_CHARACTER_CLASS upgrades the character classes.
Character.UnicodeScript.of maps each code point to its writing script, letting validation route Latin, Han, or Hiragana input by script.
Parse, divide, and compare ints in the unsigned domain so values beyond Integer.MAX_VALUE keep their meaning across parseUnsignedInt and compareUnsigned.
Java UTF-8 decoding does not strip the BOM, so Files.readString on an Excel-style export starts with U+FEFF and header matches silently fail.
Evaluate XPath expressions against a DOM document: compile once for reuse, read scalars as strings, counts as NUMBER, node sets as NODESET.
Mount a ZIP via the zipfs provider with a jar: URI and create=true, create parent directories explicitly, then read and write entries with the Files API.
Convert time zones with withZoneSameInstant to keep the same moment, or withZoneSameLocal to keep the wall clock and knowingly change the instant.
Ask the zone rule table for the offset in force at an instant, whether daylight savings applies, and when the next clock change lands.
Render readable report tables from a plain CLI with String.repeat rules and printf column widths, staying inside the standard library.
Swap a stack head with compareAndSet in a retry loop: the update succeeds only when no other thread moved the reference between read and write.
Update individual array elements with compareAndSet retry loops so several threads can bump counters in one array without locking the whole.
Move up to maxElements items out of a BlockingQueue in one locked step with drainTo, so consumer batches stay efficient and never race producers.
Timed offer and poll give up after the timeout instead of blocking forever: a full queue returns false, an empty one null, and neither path throws.
BreakIterator.getCharacterInstance splits text into user-perceived grapheme clusters: a ZWJ-joined emoji family is one character despite many code points.
Convert identifiers between camelCase and snake_case: insert underscores before capitals in one direction, capitalize after them in the other.
Follow the CLI exit-code convention: zero for success, one for business failures, two for usage errors, with diagnostics written to stderr.
Hand-roll a minimal CLI parser: --key=value options land in a map, bare switches become true, and leftover arguments stay positional.
Create a hard link with Files.createLink so both names share one inode: writes via either path are visible to both and deleting one name keeps the data.
Split a CSV line with a tiny state machine so quoted fields keep their commas and doubled quotes decode into literal quotation marks.
Bridge java.util.Date and Calendar to java.time through Instant and toInstant so old APIs and new code exchange the same moment losslessly.
Sort doubles reliably with Double.compare: it treats NaN as largest and distinguishes -0.0 from 0.0, both of which break subtraction-based comparators.
Parse ISO-8601 duration text like PT2H45M30S into a Duration, extend it, read back hour/minute/second parts, and convert to a single unit.
Give each enum constant its own behavior via an abstract method in the enum body, overridden per constant, so a new command cannot miss its implementation.