001: package org.apache.velocity.util;
002:
003: /*
004: * Licensed to the Apache Software Foundation (ASF) under one
005: * or more contributor license agreements. See the NOTICE file
006: * distributed with this work for additional information
007: * regarding copyright ownership. The ASF licenses this file
008: * to you under the Apache License, Version 2.0 (the
009: * "License"); you may not use this file except in compliance
010: * with the License. You may obtain a copy of the License at
011: *
012: * http://www.apache.org/licenses/LICENSE-2.0
013: *
014: * Unless required by applicable law or agreed to in writing,
015: * software distributed under the License is distributed on an
016: * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
017: * KIND, either express or implied. See the License for the
018: * specific language governing permissions and limitations
019: * under the License.
020: */
021:
022: /**
023: * Simple object pool. Based on ThreadPool and few other classes
024: *
025: * The pool will ignore overflow and return null if empty.
026: *
027: * @author Gal Shachor
028: * @author Costin
029: * @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a>
030: * @version $Id: SimplePool.java 463298 2006-10-12 16:10:32Z henning $
031: */
032: public final class SimplePool {
033: /*
034: * Where the objects are held.
035: */
036: private Object pool[];
037:
038: /**
039: * max amount of objects to be managed
040: * set via CTOR
041: */
042: private int max;
043:
044: /**
045: * index of previous to next
046: * free slot
047: */
048: private int current = -1;
049:
050: /**
051: * @param max
052: */
053: public SimplePool(int max) {
054: this .max = max;
055: pool = new Object[max];
056: }
057:
058: /**
059: * Add the object to the pool, silent nothing if the pool is full
060: * @param o
061: */
062: public void put(Object o) {
063: int idx = -1;
064:
065: synchronized (this ) {
066: /*
067: * if we aren't full
068: */
069:
070: if (current < max - 1) {
071: /*
072: * then increment the
073: * current index.
074: */
075: idx = ++current;
076: }
077:
078: if (idx >= 0) {
079: pool[idx] = o;
080: }
081: }
082: }
083:
084: /**
085: * Get an object from the pool, null if the pool is empty.
086: * @return The object from the pool.
087: */
088: public Object get() {
089: synchronized (this ) {
090: /*
091: * if we have any in the pool
092: */
093: if (current >= 0) {
094: /*
095: * remove the current one
096: */
097:
098: Object o = pool[current];
099: pool[current] = null;
100:
101: current--;
102:
103: return o;
104: }
105: }
106:
107: return null;
108: }
109:
110: /**
111: * Return the size of the pool
112: * @return The pool size.
113: */
114: public int getMax() {
115: return max;
116: }
117:
118: /**
119: * for testing purposes, so we can examine the pool
120: *
121: * @return Array of Objects in the pool.
122: */
123: Object[] getPool() {
124: return pool;
125: }
126: }
|