01: /*- MessageQueue.java ---------------------------------------------+
02: | |
03: | Copyright (C) 2002-2003 Joseph Monti, LlamaChat |
04: | countjoe@users.sourceforge.net |
05: | http://www.42llamas.com/LlamaChat/ |
06: | |
07: | This program is free software; you can redistribute it and/or |
08: | modify it under the terms of the GNU General Public License |
09: | as published by the Free Software Foundation; either version 2 |
10: | of the License, or (at your option) any later version |
11: | |
12: | This program is distributed in the hope that it will be useful, |
13: | but WITHOUT ANY WARRANTY; without even the implied warranty of |
14: | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
15: | GNU General Public License for more details. |
16: | |
17: | A copy of the GNU General Public License may be found in the |
18: | installation directory named "GNUGPL.txt" |
19: | |
20: +-----------------------------------------------------------------+
21: */
22:
23: package common;
24:
25: import java.util.LinkedList;
26:
27: /* -------------------- JavaDoc Information ----------------------*/
28: /**
29: * It defines 2 methods, enqueu, to put SocketData items into the internal
30: * Vector, and run, which is requred be Runnable (this is a threaded class)
31: * and grabs any items off the Vector. It uses a combination of wait() and
32: * notify() to keep the run method from polling on an empty queue.
33: * @author Joseph Monti
34: * <a href="mailto:countjoe@users.sourceforge.net">countjoe@users.sourceforge.net</a>
35: * @author <a href="http://codeconnector.sf.net/">Code Connector</a>
36: * @version 0.8
37: */
38:
39: public class MessageQueue implements Runnable {
40: private static final int MAX_SIZE = 15;
41: private LinkedList queue;
42: private SocketConnection writer;
43: private boolean running;
44: private boolean empty;
45:
46: public MessageQueue(SocketConnection w) {
47: writer = w;
48: queue = new LinkedList();
49: running = true;
50: empty = true;
51: new Thread(this ).start();
52: }
53:
54: synchronized public boolean enqueue(Object obj) {
55: queue.addLast(obj);
56: if (empty) {
57: empty = false;
58: notify();
59: }
60: if (queue.size() > MAX_SIZE) {
61: writer.close();
62: }
63: return true;
64: }
65:
66: public void run() {
67: while (running) {
68: try {
69: if (queue.size() != 0) {
70: writer._writeObject(queue.removeFirst());
71: } else {
72: empty = true;
73: synchronized (this ) {
74: while (empty) {
75: wait();
76: }
77: }
78: }
79: Thread.sleep(10);
80: } catch (InterruptedException inte) {
81: running = false;
82: }
83: }
84: }
85: }
|