01: /*
02: * <copyright>
03: * Copyright 1997-2003 BBNT Solutions, LLC
04: * under sponsorship of the Defense Advanced Research Projects Agency (DARPA).
05: *
06: * This program is free software; you can redistribute it and/or modify
07: * it under the terms of the Cougaar Open Source License as published by
08: * DARPA on the Cougaar Open Source Website (www.cougaar.org).
09: *
10: * THE COUGAAR SOFTWARE AND ANY DERIVATIVE SUPPLIED BY LICENSOR IS
11: * PROVIDED 'AS IS' WITHOUT WARRANTIES OF ANY KIND, WHETHER EXPRESS OR
12: * IMPLIED, INCLUDING (BUT NOT LIMITED TO) ALL IMPLIED WARRANTIES OF
13: * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND WITHOUT
14: * ANY WARRANTIES AS TO NON-INFRINGEMENT. IN NO EVENT SHALL COPYRIGHT
15: * HOLDER BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT OR CONSEQUENTIAL
16: * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE OF DATA OR PROFITS,
17: * TORTIOUS CONDUCT, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
18: * PERFORMANCE OF THE COUGAAR SOFTWARE.
19: * </copyright>
20: */
21:
22: package org.cougaar.core.thread;
23:
24: import org.cougaar.util.CircularQueue;
25:
26: /**
27: * The simplest thread service implementation, which runs its {@link
28: * Schedulable}s serially, uses this utility class to hold a set of {@link
29: * Schedulable}s in proper sequence.
30: */
31: final class SerialThreadQueue {
32:
33: private final CircularQueue<TrivialSchedulable> schedulables;
34: private final Object lock;
35:
36: SerialThreadQueue() {
37: schedulables = new CircularQueue<TrivialSchedulable>();
38: lock = new Object();
39: }
40:
41: int iterateOverThreads(ThreadStatusService.Body body) {
42: int count = 0;
43: TrivialSchedulable[] objects = new TrivialSchedulable[schedulables
44: .size()];
45: synchronized (lock) {
46: schedulables.toArray(objects);
47: }
48: for (TrivialSchedulable sched : objects) {
49: try {
50: body.run("root", sched);
51: count++;
52: } catch (Throwable t) {
53: // ignore
54: }
55: }
56: return count;
57: }
58:
59: Object getLock() {
60: return lock;
61: }
62:
63: void enqueue(TrivialSchedulable sched) {
64: sched.setState(CougaarThread.THREAD_PENDING);
65: synchronized (lock) {
66: if (!schedulables.contains(sched)) {
67: schedulables.add(sched);
68: lock.notify();
69: }
70: }
71: }
72:
73: // caller synchronizes
74: boolean isEmpty() {
75: return schedulables.isEmpty();
76: }
77:
78: // caller synchronizes
79: TrivialSchedulable next() {
80: if (schedulables.isEmpty())
81: return null;
82: else
83: return schedulables.next();
84: }
85: }
|