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

Code before:
            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 = currentBatch.maxBatchSize;

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

            currentBatch = null;
        }

        /**
         * Adds a flush event to the end of the event queue, after any existing writes in the queue.
         *
         * @param expectedBatchEpoch The epoch of the batch to flush.
         */
        private void enqueueAdaptiveFlush(int expectedBatchEpoch) {
            enqueueLast(new CoordinatorInternalEvent("FlushBatch", tp, () -> {
                withActiveContextOrThrow(tp, context -> {
                    // The batch could have already been flushed because it reached the maximum
                    // batch size or a transactional write came in. When this happens, we want
                    // to avoid flushing the next batch early.
                    if (context.currentBatch != null && context.batchEpoch == expectedBatchEpoch) {
                        context.flushCurrentBatch();
                    }
                });
            }));
        }


Review comment (performance):
nit: Could you please add a comment explaining why we use `currentBatch.maxBatchSize` here?

Code after:
            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.
            // We avoid querying the log's configuration for the max message size here,
            // because after a partition leadership change, this throws a NOT_LEADER_OR_FOLLOWER
            // exception. Such exceptions can propagate unexpectedly and disrupt subsequent operations.
            int maxBatchSize = currentBatch.maxBatchSize;

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

            currentBatch = null;
        }

        /**
         * Adds a flush event to the end of the event queue, after any existing writes in the queue.
         *
         * @param expectedBatchEpoch The epoch of the batch to flush.
         */
        private void enqueueAdaptiveFlush(int expectedBatchEpoch) {
            enqueueLast(new CoordinatorInternalEvent("FlushBatch", tp, () -> {
                withActiveContextOrThrow(tp, context -> {
                    // The batch could have already been flushed because it reached the maximum
                    // batch size or a transactional write came in. When this happens, we want
                    // to avoid flushing the next batch early.
                    if (context.currentBatch != null && context.batchEpoch == expectedBatchEpoch) {
                        context.flushCurrentBatch();
                    }
                });