001: /*
002: * Copyright 1999-2004 The Apache Software Foundation
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: */
016:
017: package org.apache.tomcat.util.collections;
018:
019: /**
020: * Simple object pool. Based on ThreadPool and few other classes
021: *
022: * The pool will ignore overflow and return null if empty.
023: *
024: * @author Gal Shachor
025: * @author Costin Manolache
026: */
027: public final class SimplePool {
028: /*
029: * Where the threads are held.
030: */
031: private Object pool[];
032:
033: private int max;
034: private int last;
035: private int current = -1;
036:
037: private Object lock;
038: public static final int DEFAULT_SIZE = 32;
039: static final int debug = 0;
040:
041: public SimplePool() {
042: this (DEFAULT_SIZE, DEFAULT_SIZE);
043: }
044:
045: public SimplePool(int size) {
046: this (size, size);
047: }
048:
049: public SimplePool(int size, int max) {
050: this .max = max;
051: pool = new Object[size];
052: this .last = size - 1;
053: lock = new Object();
054: }
055:
056: public void set(Object o) {
057: put(o);
058: }
059:
060: /**
061: * Add the object to the pool, silent nothing if the pool is full
062: */
063: public void put(Object o) {
064: synchronized (lock) {
065: if (current < last) {
066: current++;
067: pool[current] = o;
068: } else if (current < max) {
069: // realocate
070: int newSize = pool.length * 2;
071: if (newSize > max)
072: newSize = max + 1;
073: Object tmp[] = new Object[newSize];
074: last = newSize - 1;
075: System.arraycopy(pool, 0, tmp, 0, pool.length);
076: pool = tmp;
077: current++;
078: pool[current] = o;
079: }
080: if (debug > 0)
081: log("put " + o + " " + current + " " + max);
082: }
083: }
084:
085: /**
086: * Get an object from the pool, null if the pool is empty.
087: */
088: public Object get() {
089: Object item = null;
090: synchronized (lock) {
091: if (current >= 0) {
092: item = pool[current];
093: pool[current] = null;
094: current -= 1;
095: }
096: if (debug > 0)
097: log("get " + item + " " + current + " " + max);
098: }
099: return item;
100: }
101:
102: /**
103: * Return the size of the pool
104: */
105: public int getMax() {
106: return max;
107: }
108:
109: /**
110: * Number of object in the pool
111: */
112: public int getCount() {
113: return current + 1;
114: }
115:
116: public void shutdown() {
117: }
118:
119: private void log(String s) {
120: System.out.println("SimplePool: " + s);
121: }
122: }
|