XContentBuilder close() works only for valid json object

Whenever I use the XContentBuilder like such -

try {
  contentBuilder.startObject().startObject();
  //some logic, adding queries, etc
  contentBuilder.endObject().endObject();
} catch (Exception e) {
  //do something
} finally {
  if (contentBuilder != null)  contentBuilder.close();
}

If an exception is thrown in the logic between the "startObject" and "endObject" call, contentBuilder.close() throws an exception, "Failed to close XContentBuilder".

So the XContentBuilder, which is a Closeable, does not get closed.. does anyone have a way around this? Doing all this logic beforehand and passing only valid data to the XContentBuilder would be much messier. Shouldn't the close() method simply release the resource without doing any validations?

why dont you use a try-with resources block here? would that solve your case even though the execution path is slightly different?

Not sure how that would help, because the try-with-resources block would also internally call close() on the content builder, right? And if an exception is thrown, the close() call would in turn would throw an exception - causing the same memory leak.

I think the issue is that the close() implementation of XContentBuilder validates whether the object is closed or not - I'm not entirely sure why this is being done. This would mean that the content builder resources are never released if the json being created is invalid/hasn't been closed properly.

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.