Class PooledObjects

java.lang.Object
com.linecorp.armeria.unsafe.PooledObjects

@UnstableApi public final class PooledObjects extends Object
Utility class that provides ways to create a pooled HttpData and manage its life cycle.

Warning: Using a pooled HttpData is very advanced and can open up much more complicated management of a reference counted ByteBuf. You should only ever do this if you are very comfortable with Netty. It is recommended to also read through Reference counted objects for more information on pooled objects.

What is a pooled HttpData?

A pooled HttpData is a special variant of HttpData whose HttpData.isPooled() returns true. It's usually created via HttpData.wrap(ByteBuf) by wrapping an existing ByteBuf. It can appear when you consume data using the operations such as:

To put it another way, you'll never see a pooled HttpData if you did not use such operations. You can ignore the rest of this section if that's the case.

Any time you receive a pooled HttpData, it will have an underlying ByteBuf that must be released - failure to release the ByteBuf will result in a memory leak and poor performance. You must make sure to do this by calling HttpData.close(), usually in a try-with-resources structure to avoid side effects, e.g.


 HttpResponse res = client.get("/");
 res.aggregateWithPooledObjects(ctx.alloc(), ctx.executor())
    .thenApply(aggResp -> {
        // try-with-resources here ensures the content is released
        // if it is a pooled HttpData, or otherwise it's no-op.
        try (HttpData content = aggResp.content()) {
            if (!aggResp.status().equals(HttpStatus.OK)) {
                throw new IllegalStateException("Bad response");
            }
            try {
                return OBJECT_MAPPER.readValue(content.toInputStream(), Foo.class);
            } catch (IOException e) {
                throw new IllegalArgumentException("Bad JSON: " + content.toStringUtf8());
            }
        }
    });
 

In the above example, it is the initial try (HttpData content = ...) that ensures the data is released. Calls to methods on HttpData will all work and can be called any number of times within this block. If called after the block or a manual call to HttpData.close(), these methods will fail or corrupt data.