MaxGekk commented on code in PR #48420:
URL: https://github.com/apache/spark/pull/48420#discussion_r1796695648


##########
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:
   I would prefer to avoid the assumption about current no-op implementation. 
How about:
   ```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]

Reply via email to