1 package org.apache.velocity.util; 2 3 /* 4 * Licensed to the Apache Software Foundation (ASF) under one 5 * or more contributor license agreements. See the NOTICE file 6 * distributed with this work for additional information 7 * regarding copyright ownership. The ASF licenses this file 8 * to you under the Apache License, Version 2.0 (the 9 * "License"); you may not use this file except in compliance 10 * with the License. You may obtain a copy of the License at 11 * 12 * http://www.apache.org/licenses/LICENSE-2.0 13 * 14 * Unless required by applicable law or agreed to in writing, 15 * software distributed under the License is distributed on an 16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 17 * KIND, either express or implied. See the License for the 18 * specific language governing permissions and limitations 19 * under the License. 20 */ 21 22 /** 23 * Simple object pool. Based on ThreadPool and few other classes 24 * 25 * The pool will ignore overflow and return null if empty. 26 * 27 * @author Gal Shachor 28 * @author Costin 29 * @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a> 30 * @version $Id: SimplePool.java 463298 2006-10-12 16:10:32Z henning $ 31 */ 32 public final class SimplePool 33 { 34 /* 35 * Where the objects are held. 36 */ 37 private Object pool[]; 38 39 /** 40 * max amount of objects to be managed 41 * set via CTOR 42 */ 43 private int max; 44 45 /** 46 * index of previous to next 47 * free slot 48 */ 49 private int current=-1; 50 51 /** 52 * @param max 53 */ 54 public SimplePool(int max) 55 { 56 this.max = max; 57 pool = new Object[max]; 58 } 59 60 /** 61 * Add the object to the pool, silent nothing if the pool is full 62 * @param o 63 */ 64 public void put(Object o) 65 { 66 int idx=-1; 67 68 synchronized(this) 69 { 70 /* 71 * if we aren't full 72 */ 73 74 if (current < max - 1) 75 { 76 /* 77 * then increment the 78 * current index. 79 */ 80 idx = ++current; 81 } 82 83 if (idx >= 0) 84 { 85 pool[idx] = o; 86 } 87 } 88 } 89 90 /** 91 * Get an object from the pool, null if the pool is empty. 92 * @return The object from the pool. 93 */ 94 public Object get() 95 { 96 synchronized(this) 97 { 98 /* 99 * if we have any in the pool 100 */ 101 if( current >= 0 ) 102 { 103 /* 104 * remove the current one 105 */ 106 107 Object o = pool[current]; 108 pool[current] = null; 109 110 current--; 111 112 return o; 113 } 114 } 115 116 return null; 117 } 118 119 /** 120 * Return the size of the pool 121 * @return The pool size. 122 */ 123 public int getMax() 124 { 125 return max; 126 } 127 128 /** 129 * for testing purposes, so we can examine the pool 130 * 131 * @return Array of Objects in the pool. 132 */ 133 Object[] getPool() 134 { 135 return pool; 136 } 137 }