View Javadoc

1   /***
2    *
3    * Copyright 2004 Hiram Chirino
4    *
5    * Licensed under the Apache License, Version 2.0 (the "License");
6    * you may not use this file except in compliance with the License.
7    * You may obtain a copy of the License at
8    *
9    * http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   *
17   **/
18  package org.codehaus.activemq.journal.impl;
19  
20  import java.nio.ByteBuffer;
21  import java.util.ArrayList;
22  
23  import org.apache.commons.logging.Log;
24  import org.apache.commons.logging.LogFactory;
25  
26  /***
27   * Provides a simple pool of ByteBuffer objects.
28   * 
29   * @version $Revision: 1.1 $
30   */
31  public class ByteBufferPool {
32  	final static private Log log = LogFactory.getLog(ByteBufferPool.class);
33  	
34  	private final ArrayList pool = new ArrayList();
35  	private final int bufferSize;
36  	private final int maxBuffers;
37  	
38  	/***
39  	 * Creates a pool of 4 x 4 Meg ByteBuffers
40  	 *
41  	 */
42  	public ByteBufferPool() {
43  		this(4, 1024*1024*4);
44  	}
45  	
46  	/***
47  	 * Creates a pool of <code>bufferCount</code> ByteBuffers that are 
48  	 * directly allocated being <code>bufferSize</code> big.
49  	 * 
50  	 * @param bufferCount the number of buffers that will be in the pool.
51  	 * @param bufferSize the size of the buffers that are in the pool.
52  	 */
53  	public ByteBufferPool(int bufferCount,int bufferSize) {
54  		this.maxBuffers = bufferCount;
55  		this.bufferSize = bufferSize;
56  
57  		for (int i = 0; i < bufferCount; i++) {
58  			ByteBuffer bb = ByteBuffer.allocateDirect(bufferSize);
59  			pool.add(bb);
60  		}		
61  	}
62  	
63  	/***
64  	 * Blocks until a ByteBuffer can be retreived from the pool.
65  	 * 
66  	 * @return
67  	 * @throws InterruptedException
68  	 */
69  	public ByteBuffer getByteBuffer() throws InterruptedException {
70  		ByteBuffer answer=null;
71  		synchronized(this) {
72  			while(answer==null) {
73  				if( pool.size()>0) {
74  					answer = (ByteBuffer) pool.remove(pool.size()-1);
75  				}			
76  				if( answer==null ) {
77  					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.");
78  					this.wait();
79  				}
80  			}
81  		}
82  		return answer;
83  	}
84  	
85  	/***
86  	 * Returns a ByteBuffer to the pool.
87  	 * 
88  	 * @param buffer
89  	 */
90  	public void returnByteBuffer(ByteBuffer buffer) {
91  		buffer.clear();
92  		synchronized(this) {
93  			pool.add(buffer);
94  			this.notify();
95  		}
96  	}
97  	
98  }