01: /*
02: * GeoTools - OpenSource mapping toolkit
03: * http://geotools.org
04: * (C) 2002-2006, GeoTools Project Managment Committee (PMC)
05: *
06: * This library is free software; you can redistribute it and/or
07: * modify it under the terms of the GNU Lesser General Public
08: * License as published by the Free Software Foundation;
09: * version 2.1 of the License.
10: *
11: * This library is distributed in the hope that it will be useful,
12: * but WITHOUT ANY WARRANTY; without even the implied warranty of
13: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14: * Lesser General Public License for more details.
15: */
16: package org.geotools.xml.impl;
17:
18: /**
19: * A simple thread safe buffer.
20: *
21: * @author Justin Deoliveira, The Open Planning Project
22: *
23: */
24: public class Buffer {
25: static final int DEFAULT_SIZE = 1024;
26: Object[] buffer;
27: int in;
28: int out;
29: int size;
30: boolean closed;
31:
32: public Buffer() {
33: this (DEFAULT_SIZE);
34: }
35:
36: public Buffer(int size) {
37: buffer = new Object[size];
38: in = 0;
39: out = 0;
40: size = 0;
41: closed = false;
42: }
43:
44: public synchronized void put(Object object) {
45: while (size == buffer.length) {
46: try {
47: wait();
48: } catch (InterruptedException e) {
49: throw new RuntimeException(e);
50: }
51: }
52:
53: buffer[in++] = object;
54: in = (in == buffer.length) ? 0 : in;
55: size++;
56:
57: notifyAll();
58: }
59:
60: public synchronized Object get() {
61: while (size == 0) {
62: if (closed) {
63: return null;
64: }
65:
66: try {
67: wait(100);
68: } catch (InterruptedException e) {
69: throw new RuntimeException(e);
70: }
71: }
72:
73: Object object = buffer[out++];
74: out = (out == buffer.length) ? 0 : out;
75: size--;
76:
77: notifyAll();
78:
79: return object;
80: }
81:
82: public synchronized void close() {
83: closed = true;
84: notifyAll();
85: }
86: }
|