Advanced Java work combines type boundaries, resource ownership, concurrency, runtime inspection and external I/O contracts.
Types before casts
Start with generics and wildcard bounds, then make failure handling explicit. Use Optional for defined absence, not as a way to hide an I/O error.
Execution and ownership
A stream pipeline is not a collection copy, and a lambda is not automatically asynchronous. Keep file handles and worker lifetimes scoped to an owner that can close them.
Common Mistakes
Do not add concurrency before measuring the workload and choosing an admission policy. Do not describe an unbounded queue as safe because the worker count is fixed.
Working through this section
The curriculum below groups the canonical pages for this section. Open a lesson to see its release label, operation contract and connected topics. Examples can also be linked from another section without creating a second copy of the same page.
Compile the stated program with a compatible JDK and compare its result with the displayed output. Read the rejected-input and ownership clauses before changing the input. Local self-checks and downloaded programs do not imply a server-side code judge or a production service.
Filesystem observation
Work from observed state to an explicit decision.
- Java walkFileTree: visit failures without hiding incomplete scans
- Java WatchService: register, consume, and reset each key
- Java WatchService OVERFLOW: reconcile against directory state
- Java DirectoryStream: close iteration and reject silent truncation
- Java symbolic links: inspect attributes without claiming race safety
JDBC result contracts
Work from observed state to an explicit decision.
- Java JDBC batches: inspect update counts and own rollback
- Java ResultSet: cursor position and SQL NULL are separate states
- Java JDBC generated keys: validate one insert and one returned identity
- Java JDBC fetch size: a hint, not a memory guarantee
Subprocess ownership
Work from observed state to an explicit decision.
- Java ProcessBuilder: pass command tokens without a shell
- Java Process.waitFor timeout: terminate and reap the owned child
HTTP request and response boundaries
Choose an explicit boundary before scaling the work.
- Java HTTP query values: encode data without changing URI structure
- Java HttpClient redirects: check the next origin before resending
- Java HttpClient deadlines: separate connection and request timeouts
- Java streaming HTTP bodies: close the stream and cap retained bytes
- Java Retry-After: parse a bounded server delay without inventing a retry
- Java HttpClient cookies: make session storage an owned policy
Fork/join task ownership
Choose an explicit boundary before scaling the work.
- Java RecursiveTask: split work only above a measured threshold
- Java ForkJoinPool: own a custom pool and its shutdown
- Java ManagedBlocker: declare a rare blocking wait to the pool
- Java fork/join failures: one failed task does not roll back sibling work
- Java parallel streams: reduce values instead of mutating shared results
File channel boundaries
Separate an API observation from the business conclusion.
- Java FileChannel.write: finish the buffer before reporting success
- Java positioned FileChannel.read: detect a short record without moving the cursor
- Java FileChannel.transferTo: verify the byte count on every pass
- Java FileChannel.force: distinguish written bytes from forced storage
- Java FileLock: coordinate one byte range with a shared protocol
- Java FileChannel.truncate: cut only after validating the recovery offset
- Java AsynchronousFileChannel: own the buffer through completion
JVM management observations
Separate an API observation from the business conclusion.
- Java ThreadMXBean deadlocks: diagnose platform-thread cycles
- Java ThreadMXBean CPU time: check support and the disabled state
- Java MemoryMXBean: read used, committed, and an optional maximum
- Java ClassLoadingMXBean: separate live classes from lifetime totals
XML processing boundaries
Keep every parser and archive boundary explicit.
- Java DOM parsing: deny external XML access at the factory
- Java StAX: pull XML events under a count and entity policy
- Java XPath: compile a fixed selection, not user-supplied code
- Java XML Schema validation: use a trusted schema without external fetches
- Java XML Transformer: bound serialized output and external access
- Java XML namespaces: select by URI and local name
Archive and compression boundaries
Keep every parser and archive boundary explicit.
- Java GZIPInputStream: cap bytes after decompression
- Java GZIPOutputStream: close before using the compressed bytes
- Java ZipFile entries: reject duplicate names before selection
- Java ZIP CRC32: detect corruption without claiming authenticity
- Java ZipOutputStream: close each entry and the archive before publication
Concurrent maps and snapshots
Choose a structure for the actual concurrency contract.
- Java ConcurrentHashMap.computeIfAbsent: create a counter once per key
- Java ConcurrentSkipListMap: inspect an ordered time window
- Java CopyOnWriteArrayList: dispatch against a listener snapshot
- Java AtomicReference: publish one immutable map snapshot
Timed queues and handoffs
Choose a structure for the actual concurrency contract.
- Java DelayQueue: release retry work only after its deadline
- Java Exchanger: swap buffers at a two-party rendezvous
- Java LinkedTransferQueue: wait until a consumer receives work
Thread state and metrics
Choose a structure for the actual concurrency contract.
- Java LongAccumulator: track a concurrent high-water mark
- Java ThreadLocal: restore request context when a pooled thread is reused
- Java LockSupport: park only inside a checked condition loop
Generics at API boundaries
Read the runtime boundary behind each language feature.
- Java generic wildcards: copy from a producer into a consumer
- Java type erasure: validate elements with an explicit Class token
- Java bridge methods: preserve overrides after generic erasure
Dispatch and data contracts
Read the runtime boundary behind each language feature.
- Java interface defaults: resolve a two-parent method conflict
- Java compact record constructors: normalize before field assignment
- Java instanceof patterns: keep a narrowed value inside its valid scope
- Java switch expressions: return one value from every state
- Java sealed hierarchies: switch over permitted request kinds
Metadata and constant behavior
Read the runtime boundary behind each language feature.
- Java annotation retention: expose metadata without pretending it enforces policy
- Java repeatable annotations: read every declared routing label
- Java enum constant bodies: keep each fee rule with its tier
JDBC: Transaction and capability boundaries
Inspect each driver and transaction contract.
- Java JDBC savepoints: roll back one optional step inside a transaction
- Java JDBC query timeout: bound a statement without claiming a whole-request deadline
- Java JDBC read-only mode: use the hint without treating it as authorization
JDBC: Parameter and row boundaries
Inspect each driver and transaction contract.
- Java JDBC setNull: bind a nullable column with its SQL type
- Java JDBC ResultSet binary streams: read before advancing the cursor
- Java JDBC binary parameters: cap bytes before binding a BLOB
JDBC: Diagnostics and metadata
Inspect each driver and transaction contract.
- Java SQLWarning: inspect nonfatal database diagnostics before reuse
- Java DatabaseMetaData: check features before depending on them
- Java JDBC cursor holdability: choose what commit does to a ResultSet
- Java SQLException chains: preserve SQLState and linked failures
Async: Dependent stages
Follow the asynchronous operation's actual contract.
- Java thenCompose: flatten a dependent asynchronous request
- Java thenCombine: join two independent results without serializing them
Async: Race and recovery
Follow the asynchronous operation's actual contract.
- Java applyToEither: use the first normal result of two stages
- Java exceptionallyCompose: recover with another asynchronous stage
Async: Completion boundaries
Follow the asynchronous operation's actual contract.
- Java CompletableFuture join versus get: preserve failure and interruption contracts
- Java CompletableFuture cancellation: distinguish result status from worker interruption
Async: Bulk executor calls
Follow the asynchronous operation's actual contract.
- Java ExecutorService invokeAll: wait for a bounded batch with a deadline
- Java ExecutorService invokeAny: return one successful result from competing tasks
Runtime: Reflective invocation
Inspect the boundaries before invoking or loading.
- Java reflection: separate an invoked method failure from lookup failure
- Java getMethod: resolve an overload by its exact parameter types
- Java MethodHandle.invokeExact: make the call-site type part of the contract
Runtime: Module boundaries
Inspect the boundaries before invoking or loading.
- Java trySetAccessible: handle a denied deep-reflection request
- Java modules: distinguish exported APIs from open packages
Runtime: Runtime adapters
Inspect the boundaries before invoking or loading.
- Java dynamic proxies: define Object-method behavior explicitly
- Java ServiceLoader: treat provider discovery as fallible startup work
- Java Class.forName: inspect an allowlisted class without initializing it
Collections: Compact sets and views
Choose the data structure with its resource and view contract in mind.
- Java BitSet: distinguish logical length, capacity, and set-bit count
- Java BitSet nextSetBit: scan a bounded index range without walking gaps
- Java EnumSet complementOf: derive a default-deny capability set
- Java EnumSet: retain element type when a source collection is empty
- Java NavigableSet subSet: account for a live backed range
Collections: Concurrent collections
Choose the data structure with its resource and view contract in mind.
