/*
* 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 com.google.code.yanf4j.buffer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.HashMap;
import java.util.Map;
import java.util.Queue;
import com.google.code.yanf4j.util.CircularQueue;
/**
* An {@link IoBufferAllocator} 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 IoBuffer} 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 IoBuffer#free()} is called properly.
*
* @author The Apache MINA Project ([email protected])
* @version $Rev: 671827 $, $Date: 2008-06-26 10:49:48 +0200 (Thu, 26 Jun 2008) $
*/
public class CachedBufferAllocator implements IoBufferAllocator {
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