Examples

Page 28 of 50

Browse code examples

javaSnippet

EnumSet Compact Constant Set

Model fixed option sets with EnumSet: noneOf, of, range, and complementOf build bit-packed sets of enum constants that iterate in declaration order.

javaSnippet

Executor InvokeAny First Success

invokeAny races the same request across worker tasks, returns the first success, cancels the rest, and throws ExecutionException only when every task fails.

javaSnippet

Executor Rejection Policy Choices

See what a saturated ThreadPoolExecutor does with new tasks: AbortPolicy throws RejectedExecutionException, CallerRunsPolicy runs the task in the submitter.

javaSnippet

Lazy Supplier Memoized Value

Wrap an expensive initializer in a memoized Supplier so the value is computed on first get and reused afterwards without re-running the loader.

javaSnippet

Regex Named Capturing Groups

Extract structured fields from log lines and email addresses with named capturing groups, reading each match by name instead of fragile numbered group indexes.

javaSnippet

String Split Regex Pitfalls

String.split treats its argument as a regex: dots swallow whole strings, trailing empties vanish by default, and a negative limit is what preserves them.

javaSnippet

Switch Expressions Arrow Yield

Return values directly from switch expressions with arrow labels and yield, gaining exhaustive enum checking without default branches or fall-through.

javaSnippet

SynchronousQueue Direct Handoff

Hand work straight from producer to consumer with a zero-capacity queue: put() blocks until another thread takes, so nothing is buffered in between.

javaSnippet

System Logger Minimal Setup

Log through the JDK built-in System.Logger facade: zero dependencies, MessageFormat-style placeholders, and Supplier messages built only when the level is on.

javaSnippet

UUID Random Parse Roundtrip

Generate random UUIDv4 identifiers with randomUUID, parse canonical text back with fromString, and rely on fromString rejecting malformed input.

javaSnippet

Wait NotifyAll Guarded Block

Coordinate threads on one monitor with wait and notifyAll inside a synchronized guarded block that rechecks its condition in a while loop.

javaSnippet

YearMonth Expiry Validation

Validate card expiry printed as MM/yy with YearMonth.parse: the printed month stays valid through its last day, so only earlier months count as expired.

javaSnippet

Zip Filesystem Read Entries

Open a zip archive as a filesystem with FileSystems.newFileSystem so Path APIs list and read entries without unpacking the archive first.