001/* 002 * ModeShape (http://www.modeshape.org) 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package org.modeshape.schematic.internal.io; 017 018import java.nio.ByteBuffer; 019import java.nio.CharBuffer; 020import org.modeshape.schematic.annotation.NotThreadSafe; 021 022/** 023 * A cache of ByteBuffer, used in {@link BsonDataInput}. 024 * 025 * @author Randall Hauch <rhauch@redhat.com> (C) 2011 Red Hat Inc. 026 */ 027@NotThreadSafe 028public class BufferCache { 029 /** 030 * The minimum number of bytes in each buffer. 031 */ 032 public static final int MINIMUM_SIZE = 1048 * 8; 033 /** 034 * The maximum number of bytes in each cached buffer. If a buffer is too large, then using it and caching it in-memory will be 035 * too costly. 036 */ 037 public static final int MAXIMUM_SIZE = 1048 * 80; 038 039 private ByteBuffer byteBuffer = ByteBuffer.allocate(MINIMUM_SIZE); 040 private CharBuffer charBuffer = CharBuffer.allocate(MINIMUM_SIZE); 041 042 public ByteBuffer getByteBuffer( int minimumSize ) { 043 minimumSize = Math.max(minimumSize, MINIMUM_SIZE); 044 ByteBuffer buffer = byteBuffer; 045 if (buffer == null || buffer.capacity() < minimumSize) { 046 // Allocate a new one ... 047 buffer = ByteBuffer.allocate(minimumSize); 048 } else { 049 // The existing one is good enough ... 050 byteBuffer = null; 051 buffer.clear(); 052 } 053 return buffer; 054 } 055 056 public CharBuffer getCharBuffer( int minimumSize ) { 057 minimumSize = Math.max(minimumSize, MINIMUM_SIZE); 058 CharBuffer buffer = charBuffer; 059 if (buffer == null || buffer.capacity() < minimumSize) { 060 // Allocate a new one ... 061 buffer = CharBuffer.allocate(minimumSize); 062 } else { 063 // The existing one is good enough ... 064 charBuffer = null; 065 // But be sure to clear it out ... 066 buffer.clear(); 067 } 068 return buffer; 069 } 070 071 public void checkin( ByteBuffer byteBuffer ) { 072 if (byteBuffer.capacity() < MAXIMUM_SIZE) { 073 this.byteBuffer = byteBuffer; 074 } 075 } 076 077 public void checkin( CharBuffer charBuffer ) { 078 if (charBuffer.capacity() < MAXIMUM_SIZE) { 079 this.charBuffer = charBuffer; 080 } 081 } 082}