/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package io.craft.atom.util.buffer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.HashMap;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
/**
* An {@link BufferAllocator} that caches the buffers which are likely to
* be reused during auto-expansion of the buffers.
*
* In {@link SimpleBufferAllocator}, the underlying {@link ByteBuffer} of
* the {@link AdaptiveByteBuffer} is reallocated on its capacity change, which means
* the newly allocated bigger {@link ByteBuffer} replaces the old small
* {@link ByteBuffer}. Consequently, the old {@link ByteBuffer} is marked
* for garbage collection.
*
* It's not a problem in most cases as long as the capacity change doesn't
* happen frequently. However, once it happens too often, it burdens the
* VM and the cost of filling the newly allocated {@link ByteBuffer} with
* {@code NUL} surpass the cost of accessing the cache. In 2 dual-core
* Opteron Italy 270 processors, {@link CachedBufferAllocator} outperformed
* {@link SimpleBufferAllocator} in the following situation:
*
* - when a 32 bytes buffer is expanded 4 or more times,
* - when a 64 bytes buffer is expanded 4 or more times,
* - when a 128 bytes buffer is expanded 2 or more times,
* - and when a 256 bytes or bigger buffer is expanded 1 or more times.
*
* Please note the observation above is subject to change in a different
* environment.
*
* {@link CachedBufferAllocator} uses {@link ThreadLocal} to store the cached
* buffer, allocates buffers whose capacity is power of 2 only and provides
* performance advantage if {@link AdaptiveByteBuffer#free()} is called properly.
*
* @author Apache MINA Project
* @author mindwind
*/
public class CachedBufferAllocator implements BufferAllocator {
private static final int DEFAULT_MAX_POOL_SIZE = 8 ;
private static final int DEFAULT_MAX_CACHED_BUFFER_SIZE = 1 << 18; // 256KB
private final int maxPoolSize ;
private final int maxCachedBufferSize;
private final ThreadLocal