@Override
    public void release(ByteBuffer previouslyAllocated) {
        lock.lock();
        try {
            previouslyAllocated.clear();

            if (previouslyAllocated.capacity() != batchSize) {
                throw new IllegalArgumentException("Released buffer with unexpected size "
                    + previouslyAllocated.capacity());
            }

            // Free the buffer if the number of pooled buffers is already the maximum number of batches.
            // Otherwise return the buffer to the memory pool.
            if (free.size() >= maxRetainedBatches) {
                numAllocatedBatches--;
            } else {
                free.offer(previouslyAllocated);
            }
        } finally {
            lock.unlock();
        }
    }
@Test
    public void testReleaseBufferNotMatchingBatchSize() {
        int batchSize = 1024;
        int maxRetainedBatches = 3;

        BatchMemoryPool pool = new BatchMemoryPool(maxRetainedBatches, batchSize);
        ByteBuffer buffer = ByteBuffer.allocate(1023);
        assertThrows(IllegalArgumentException.class, () -> pool.release(buffer));
    }