/**
 *
 * Copyright 2004 Hiram Chirino
 *
 * Licensed 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 org.codehaus.activemq.journal.impl;

import java.nio.ByteBuffer;
import java.util.ArrayList;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Provides a simple pool of ByteBuffer objects.
 * 
 * @version $Revision: 1.1 $
 */
public class ByteBufferPool {
	final static private Log log = LogFactory.getLog(ByteBufferPool.class);
	
	private final ArrayList pool = new ArrayList();
	private final int bufferSize;
	private final int maxBuffers;
	
	/**
	 * Creates a pool of 4 x 4 Meg ByteBuffers
	 *
	 */
	public ByteBufferPool() {
		this(4, 1024*1024*4);
	}
	
	/**
	 * Creates a pool of <code>bufferCount</code> ByteBuffers that are 
	 * directly allocated being <code>bufferSize</code> big.
	 * 
	 * @param bufferCount the number of buffers that will be in the pool.
	 * @param bufferSize the size of the buffers that are in the pool.
	 */
	public ByteBufferPool(int bufferCount,int bufferSize) {
		this.maxBuffers = bufferCount;
		this.bufferSize = bufferSize;

		for (int i = 0; i < bufferCount; i++) {
			ByteBuffer bb = ByteBuffer.allocateDirect(bufferSize);
			pool.add(bb);
		}		
	}
	
	/**
	 * Blocks until a ByteBuffer can be retreived from the pool.
	 * 
	 * @return
	 * @throws InterruptedException
	 */
	public ByteBuffer getByteBuffer() throws InterruptedException {
		ByteBuffer answer=null;
		synchronized(this) {
			while(answer==null) {
				if( pool.size()>0) {
					answer = (ByteBuffer) pool.remove(pool.size()-1);
				}			
				if( answer==null ) {
					log.warn("Performance Warning: Buffer pool ran out of buffers.  Waiting for buffer to be returned.  System may be uner heavy load or you may need to configure more buffers in the pool.");
					this.wait();
				}
			}
		}
		return answer;
	}
	
	/**
	 * Returns a ByteBuffer to the pool.
	 * 
	 * @param buffer
	 */
	public void returnByteBuffer(ByteBuffer buffer) {
		buffer.clear();
		synchronized(this) {
			pool.add(buffer);
			this.notify();
		}
	}
	
}
