Java Examples

Page 6 of 7

Browse Java examples

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.

javaSnippet

BigDecimal Scale And Rounding

Do money math with BigDecimal instead of double: explicit setScale with RoundingMode, and compareTo instead of equals because scale makes 2.50 differ from 2.5.

javaSnippet

Exchanger Swap Between Two Threads

Meet another thread at an Exchanger and trade objects in one atomic handoff — exchange() blocks until both sides arrive, then returns the partner object.

javaSnippet

LinkedHashMap Access-Order LRU

Bound a cache with LinkedHashMap in access order: get refreshes recency and removeEldestEntry evicts the least recently used key once capacity is exceeded.

javaSnippet

StampedLock Optimistic Read

Take an optimistic snapshot with tryOptimisticRead and validate the stamp; fall back to a real read lock only when a write interfered mid-read.

javaSnippet

StringJoiner Delimited Output

Assemble delimited output with StringJoiner: prefix and suffix framing, an explicit empty value, and merge that reuses the first joiner's delimiter.

javaSnippet

ThreadLocal Per-Thread State

Give each thread its own counter via ThreadLocal.withInitial so mutable per-thread state needs no locking; clear it before pooled threads get reused.

javaSnippet

CountDownLatch Readiness Gate

Gate startup on several one-shot signals with CountDownLatch and await(timeout), so boot either proceeds when all dependencies report ready or aborts.

javaSnippet

CyclicBarrier Phased Workers

Synchronize phased work with a reusable CyclicBarrier: workers await at the barrier each round and the last arrival runs the barrier action.

javaSnippet

WatchService Directory Events

Watch a directory for ENTRY_CREATE, ENTRY_MODIFY, and ENTRY_DELETE with WatchService, polling keys with a timeout and resetting them after each drain.

javaSnippet

Atomic Variables CAS Counter

Track concurrent metrics with AtomicLong and LongAdder, and drive a compare-and-set loop when the update depends on the previous value.