01: /*
02: * Copyright (c) 2007 XStream Committers.
03: * All rights reserved.
04: *
05: * The software in this package is published under the terms of the BSD
06: * style license a copy of which has been included with this distribution in
07: * the LICENSE.txt file.
08: *
09: * Created on 10. May 2007 by Joerg Schaible
10: */
11: package com.thoughtworks.xstream.core.util;
12:
13: /**
14: * A simple pool implementation.
15: *
16: * @author Jörg Schaible
17: * @author Joe Walnes
18: */
19: public class Pool {
20:
21: public interface Factory {
22: public Object newInstance();
23: }
24:
25: private final int initialPoolSize;
26: private final int maxPoolSize;
27: private final Factory factory;
28: private transient Object[] pool;
29: private transient int nextAvailable;
30: private transient Object mutex = new Object();
31:
32: public Pool(int initialPoolSize, int maxPoolSize, Factory factory) {
33: this .initialPoolSize = initialPoolSize;
34: this .maxPoolSize = maxPoolSize;
35: this .factory = factory;
36: }
37:
38: public Object fetchFromPool() {
39: Object result;
40: synchronized (mutex) {
41: if (pool == null) {
42: pool = new Object[maxPoolSize];
43: for (nextAvailable = initialPoolSize; nextAvailable > 0;) {
44: putInPool(factory.newInstance());
45: }
46: }
47: while (nextAvailable == maxPoolSize) {
48: try {
49: mutex.wait();
50: } catch (InterruptedException e) {
51: throw new RuntimeException(
52: "Interrupted whilst waiting "
53: + "for a free item in the pool : "
54: + e.getMessage());
55: }
56: }
57: result = pool[nextAvailable++];
58: if (result == null) {
59: result = factory.newInstance();
60: putInPool(result);
61: ++nextAvailable;
62: }
63: }
64: return result;
65: }
66:
67: protected void putInPool(Object object) {
68: synchronized (mutex) {
69: pool[--nextAvailable] = object;
70: mutex.notify();
71: }
72: }
73:
74: private Object readResolve() {
75: mutex = new Object();
76: return this;
77: }
78: }
|