Java Examples

Page 4 of 7

Browse Java examples

javaSnippet

Wrap Words To A Fixed Width

Break text into lines no wider than the limit with a greedy pass: fill each line with as many words as fit, then start the next line.

javaSnippet

Double Checked Locking Singleton

Build a lazy thread-safe singleton with volatile and double-checked locking, where the second check inside the synchronized block prevents duplicate builds.

javaSnippet

ExecutionException Cause Chain

Unwrap checked failures from concurrent tasks with ExecutionException.getCause, restoring the original exception instead of wrapping it in another layer.

javaSnippet

Server Socket Accept Loop

Accept one loopback client with ServerSocket, echo a line back through the socket streams, and close both ends with try-with-resources.

javaSnippet

Shutdown Hooks Run At JVM Exit

Register JVM shutdown hooks with Runtime.addShutdownHook, verify they can be removed, and use them for final flush or cleanup on normal exit.