Java Materials
← Core Java · Chapter 8

I/O, NIO, networking and serialization

Use byte streams for binary content and readers or writers for characters. A charset decoder transforms bytes into text. Buffering reduces small I/O calls, but still requires bounded processing for large input. Define protocol framing and timeouts independently from data conversion.

Streaming bytes, encoding and buffer state

Definition:

A ByteBuffer tracks position, limit and capacity for bounded byte transfer.

Explanation:

A buffer separates storage capacity, position and limit.

Illustration image:

Streaming bytes, encoding and buffer state. Capacity 8 · put A: position 1 · flip: limit 1 · get reads AStreaming bytes, encoding and buffer stateSource or actorCapacity 8First boundaryput A: position 1Inspected stateflip: limit 1Observable effectget reads A
Capacity 8 · put A: position 1 · flip: limit 1 · get reads A

Example:

Worked Java example · see surrounding context in notes
var buffer = java.nio.ByteBuffer.allocate(8);
buffer.put((byte)65);
buffer.flip();
System.out.println((char) buffer.get());

Expected behavior. Prints A. After flip, the readable limit is the prior write position.

Internal working:

For a channel read into a ByteBuffer, flip prepares produced bytes for consumption; compact preserves unread bytes before additional reads. A network read can return partial protocol data. Decode chunks with a CharsetDecoder when multibyte sequences can straddle chunks. Close streams returned by Files.lines and similar operations.

Interview questions:

What does flip do after a channel read?

It makes the old position the reading limit and resets the position to zero.

HTTP deadlines and ambiguous writes

Definition:

An HTTP deadline bounds client waiting for a request and cannot guarantee the remote action stopped.

Explanation:

Set connection and per-request deadlines separately.

Illustration image:

HTTP deadlines and ambiguous writes. Connection established · Write reaches server · Response lost · Caller sees timeoutHTTP deadlines and ambiguous writesSource or actorConnection establishedFirst boundaryWrite reaches serverInspected stateResponse lostObservable effectCaller sees timeout
Connection established · Write reaches server · Response lost · Caller sees timeout

Example:

Worked Java example · see surrounding context in notes
var client = java.net.http.HttpClient.newBuilder()
    .connectTimeout(java.time.Duration.ofSeconds(2)).build();
var request = java.net.http.HttpRequest.newBuilder(uri)
    .timeout(java.time.Duration.ofSeconds(3)).GET().build();
var response = client.send(request, java.net.http.HttpResponse.BodyHandlers.ofString());

Expected behavior. Handle response.statusCode explicitly. Bound or stream the body in production instead of assuming it fits in memory.

Internal working:

A successful transport does not imply HTTP success. Canceling a future or receiving a timeout does not prove the remote service skipped the write. For retries, reuse the same application idempotency key when the contract supports it and verify the previously unknown outcome.

Interview questions:

Why can a timeout after POST leave the outcome unknown?

The server may have committed before the response was lost; use a stable idempotency key and reconcile.

Serialization boundaries and compatibility

Definition:

A deserialization boundary converts encoded data into typed objects under a policy.

Explanation:

Java native serialization restores an object graph and can invoke deserialization hooks.

Illustration image:

Serialization boundaries and compatibility. Encoded stream · Class and graph filter · Decoded DTO · Business validationSerialization boundaries and compatibilitySource or actorEncoded streamFirst boundaryClass and graph filterInspected stateDecoded DTOObservable effectBusiness validation
Encoded stream · Class and graph filter · Decoded DTO · Business validation

Example:

Worked Java example · see surrounding context in notes
var filter = java.io.ObjectInputFilter.Config.createFilter(
    "maxdepth=6;maxarray=128;maxrefs=200;com.example.messages.*;!*");
try (var in = new java.io.ObjectInputStream(trustedStream)) {
    in.setObjectInputFilter(filter);
    Object restored = in.readObject();
}

Expected behavior. Objects outside the configured policy are rejected; a permitted class still needs field and business validation.

Internal working:

Keep it limited to deliberate legacy boundaries with class and resource filters. serialVersionUID contributes to class compatibility but does not define a robust public schema. For service APIs use explicit DTOs, versioned formats, bounded input and separate authorization.

Interview questions:

What remains necessary after a deserialization filter accepts a class?

Validate field values and business authorization before performing any effect.

Reference subtopics

Paths and channels

Path and Files provide filesystem operations. Files.lines, list and walk can retain open resources and belong in try-with-resources. Buffers maintain position and limit; flip prepares written data for reading. Channels may support partial reads or writes. Selectors multiplex readiness for nonblocking selectable channels and the application remains responsible for framing and backpressure.

Networking and HTTP

Separate connection establishment from read or request deadlines. Socket reads can return less than the requested length. HttpClient, standardized in 11, offers send and sendAsync. Check HTTP status and consume or close streaming bodies. Cancellation of a future does not universally undo the remote action. Preserve idempotency at the business boundary.

Serialization and wire formats

Serializable enables native object serialization. transient skips normal field serialization and serialVersionUID participates in compatibility. Deserialization filters constrain allowed shapes, depth or classes for legacy streams. For external boundaries prefer versioned formats with explicit schemas and validation. Treat parsing and authorization as different problems.

Run the complete Java labs ↗ · Java reference ↗