Repository: apache/kafka
File: coordinator-common/src/main/java/org/apache/kafka/coordinator/common/runtime/CoordinatorRuntime.java (Java)

Code before:
                highWatermarklistener = null;
            }
            timer.cancelAll();
            executor.cancelAll();
            deferredEventQueue.failAll(Errors.NOT_COORDINATOR.exception());
            failCurrentBatch(Errors.NOT_COORDINATOR.exception());
            if (coordinator != null) {
                try {
                    coordinator.onUnloaded();
                } catch (Throwable ex) {
                    log.error("Failed to unload coordinator for {} due to {}.", tp, ex.getMessage(), ex);
                }
            }
            coordinator = null;
        }

        /**
         * Frees the current batch.
         */
        private void freeCurrentBatch() {
            // Cancel the linger timeout.
            currentBatch.lingerTimeoutTask.ifPresent(TimerTask::cancel);

            // Release the buffer.
            int maxBatchSize = partitionWriter.config(tp).maxMessageSize();
            if (currentBatch.builder.buffer().capacity() > maxBatchSize) {
                // If the buffer exceeds the maxBatchSize, we should revert to using the original smaller buffer to avoid retaining the larger one.
                bufferSupplier.release(currentBatch.buffer);
            } else {
                bufferSupplier.release(currentBatch.builder.buffer());
            }


            currentBatch = null;
        }

        /**
         * Flushes the current (or pending) batch to the log. When the batch is written
         * locally, a new snapshot is created in the snapshot registry and the events
         * associated with the batch are added to the deferred event queue.
         */
        private void flushCurrentBatch() {
            if (currentBatch != null) {
                try {
                    if (currentBatch.builder.numRecords() == 0) {
                        // The only way we can get here is if append() has failed in an unexpected
                        // way and left an empty batch. Try to clean it up.
                        log.debug("Tried to flush an empty batch for {}.", tp);
                        // There should not be any deferred events attached to the batch. We fail
                        // the batch just in case. As a side effect, coordinator state is also
                        // reverted, but there should be no changes since the batch was empty.

Review comment (performance):
When we create the batch, we set `maxMessageSize` as the limit so it should not create a buffer larger than it as we don't append to the batch if it does not have room for it.

Code after:
                highWatermarklistener = null;
            }
            timer.cancelAll();
            executor.cancelAll();
            deferredEventQueue.failAll(Errors.NOT_COORDINATOR.exception());
            failCurrentBatch(Errors.NOT_COORDINATOR.exception());
            if (coordinator != null) {
                try {
                    coordinator.onUnloaded();
                } catch (Throwable ex) {
                    log.error("Failed to unload coordinator for {} due to {}.", tp, ex.getMessage(), ex);
                }
            }
            coordinator = null;
        }

        /**
         * Frees the current batch.
         */
        private void freeCurrentBatch() {
            // Cancel the linger timeout.
            currentBatch.lingerTimeoutTask.ifPresent(TimerTask::cancel);

            // Release the buffer only if it is not larger than the maxBatchSize.
            int maxBatchSize = partitionWriter.config(tp).maxMessageSize();

            if (currentBatch.builder.buffer().capacity() <= maxBatchSize) {
                bufferSupplier.release(currentBatch.builder.buffer());
            } else if (currentBatch.buffer.capacity() <= maxBatchSize) {
                bufferSupplier.release(currentBatch.buffer);
            }

            currentBatch = null;
        }

        /**
         * Flushes the current (or pending) batch to the log. When the batch is written
         * locally, a new snapshot is created in the snapshot registry and the events
         * associated with the batch are added to the deferred event queue.
         */
        private void flushCurrentBatch() {
            if (currentBatch != null) {
                try {
                    if (currentBatch.builder.numRecords() == 0) {
                        // The only way we can get here is if append() has failed in an unexpected
                        // way and left an empty batch. Try to clean it up.
                        log.debug("Tried to flush an empty batch for {}.", tp);
                        // There should not be any deferred events attached to the batch. We fail
                        // the batch just in case. As a side effect, coordinator state is also
                        // reverted, but there should be no changes since the batch was empty.
                        failCurrentBatch(new IllegalStateException("Record batch was empty"));