Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[SPARK-45814][CONNECT][SQL]Make ArrowConverters.createEmptyArrowBatch call close() to avoid memory leak #43691

Closed
wants to merge 4 commits into from
Closed
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -80,7 +80,7 @@ private[sql] object ArrowConverters extends Logging {
maxRecordsPerBatch: Long,
timeZoneId: String,
errorOnDuplicatedFieldNames: Boolean,
context: TaskContext) extends Iterator[Array[Byte]] {
context: TaskContext) extends Iterator[Array[Byte]] with AutoCloseable {

protected val arrowSchema =
ArrowUtils.toArrowSchema(schema, timeZoneId, errorOnDuplicatedFieldNames)
Expand All @@ -93,13 +93,11 @@ private[sql] object ArrowConverters extends Logging {
protected val arrowWriter = ArrowWriter.create(root)

Option(context).foreach {_.addTaskCompletionListener[Unit] { _ =>
root.close()
allocator.close()
close()
}}

override def hasNext: Boolean = rowIter.hasNext || {
root.close()
allocator.close()
close()
false
}

Expand All @@ -124,6 +122,11 @@ private[sql] object ArrowConverters extends Logging {

out.toByteArray
}

override def close(): Unit = {
root.close()
allocator.close()
}
}

private[sql] class ArrowBatchWithSchemaIterator(
Expand Down Expand Up @@ -226,11 +229,15 @@ private[sql] object ArrowConverters extends Logging {
schema: StructType,
timeZoneId: String,
errorOnDuplicatedFieldNames: Boolean): Array[Byte] = {
new ArrowBatchWithSchemaIterator(
val batches = new ArrowBatchWithSchemaIterator(
Iterator.empty, schema, 0L, 0L,
timeZoneId, errorOnDuplicatedFieldNames, TaskContext.get()) {
override def hasNext: Boolean = true
}.next()
}
val emptyBatch = batches.next()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Utils.tryWithSafeFinally {
  batches.next()
} {
  if (TaskContext.get() == null) { // If taskContext is not null, it can be successfully closed, right?
    batches.close()
  }
}

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's right

// SPARK-45814: We need to call `close()` to avoid memory leak.
batches.close()
emptyBatch
}

/**
Expand Down