panbingkun commented on code in PR #48420:
URL: https://github.com/apache/spark/pull/48420#discussion_r1797531964
##########
common/utils/src/main/scala/org/apache/spark/util/JsonUtils.scala:
##########
@@ -31,12 +31,21 @@ private[spark] trait JsonUtils {
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
def toJsonString(block: JsonGenerator => Unit): String = {
- val baos = new ByteArrayOutputStream()
- val generator = mapper.createGenerator(baos, JsonEncoding.UTF8)
- block(generator)
- generator.close()
- baos.close()
- new String(baos.toByteArray, StandardCharsets.UTF_8)
+ var baos: ByteArrayOutputStream = null
+ var generator: JsonGenerator = null
+ try {
+ baos = new ByteArrayOutputStream()
+ generator = mapper.createGenerator(baos, JsonEncoding.UTF8)
+ block(generator)
+ new String(baos.toByteArray, StandardCharsets.UTF_8)
+ } finally {
+ if (generator != null) {
+ generator.close()
+ }
+ if (baos != null) {
+ baos.close()
Review Comment:
Only after `generator` executes `close`, `baos` is the final data
(dependency on `flush`), so I have slightly adjusted the above code to:
```scala
tryWithResource(new ByteArrayOutputStream()) { baos =>
tryWithResource(mapper.createGenerator(baos, JsonEncoding.UTF8)) {
generator =>
block(generator)
}
new String(baos.toByteArray, StandardCharsets.UTF_8)
}
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]