Skip to content

Bad example in JavaDoc of InputStreamResponseListener #12916

@mperktold

Description

@mperktold

Jetty version(s)
12.0.17

Jetty Environment
core (client)

Java version/vendor (use: java -version)
OpenJDK 64-Bit Server VM Temurin-21.0.6+7 (build 21.0.6+7-LTS, mixed mode, sharing)

OS type/version
Windows 11

Description
The class documentation of InputStreamResponseListener includes the following example to demonstrate its usage:

InputStreamResponseListener listener = new InputStreamResponseListener();
client.newRequest(...).send(listener);

// Wait for the response headers to arrive
Response response = listener.get(5, TimeUnit.SECONDS);
if (response.getStatus() == 200)
{
    // Obtain the input stream on the response content
    try (InputStream input = listener.getInputStream())
    {
        // Read the response content
    }
}

This works but will leak resources if the status is not 200, because then we never read the content. Therefore, the response stays open forever, or at least until some timeout occurs.

It would be better to abort the response if we don't read it:

Response response = listener.get(5, TimeUnit.SECONDS);
if (response.getStatus() == 200)
{
    // ...
}
else
    response.abort(new CancellationException());

To make this easier, you could consider making the whole listener AutoCloseable, not just the input stream, so one could use try-with-resources on the listener to make sure the response is completed at the end:

try (InputStreamResponseListener listener = new InputStreamResponseListener())
{
    client.newRequest(...).send(listener);
    Response response = listener.get(5, TimeUnit.SECONDS);
    if (response.getStatus() == 200)
    {
        // ...
    }
}

Metadata

Metadata

Assignees

Labels

BugFor general bugs on Jetty side

Type

No type
No fields configured for issues without a type.

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions