Skip to content

Race condition in the BodyDeferringAsyncHandler example #1451

Closed
@ancwrd1

Description

@ancwrd1

This code shown as an example is actually incorrect:

     PipedOutputStream pout = new PipedOutputStream();
     BodyDeferringAsyncHandler bdah = new BodyDeferringAsyncHandler(pout);
     // client executes async
     Future<Response> fr = client.prepareGet("http://foo.com/aresource").execute(bdah);
     // main thread will block here until headers are available
     Response response = bdah.getResponse();
     if (response.getStatusCode() == 200) {
      InputStream pin = new BodyDeferringInputStream(fr,new PipedInputStream(pout));
      // consume InputStream
      ...
     } else {
      // handle unexpected response status code
      ...
     }

The reason is that the bdah.getResponse might write into the pout channel which is not connected yet.
This has been observed in the tests.
I think a better code would be:

     PipedOutputStream pout = new PipedOutputStream();
     BodyDeferringAsyncHandler bdah = new BodyDeferringAsyncHandler(pout);
     // client executes async
     Future<Response> fr = client.prepareGet("http://foo.com/aresource").execute(bdah);

     InputStream pin = new BodyDeferringInputStream(fr,new PipedInputStream(pout));

     // main thread will block here until headers are available
     Response response = bdah.getResponse();
     if (response.getStatusCode() == 200) {
      // consume pin
      ...
     } else {
      // handle unexpected response status code
      ...
     }

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions