01: /*
02: * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright
03: * notice. All rights reserved.
04: */
05: package com.tc.net.protocol.delivery;
06:
07: import com.tc.async.api.EventContext;
08: import com.tc.async.api.Sink;
09:
10: import java.util.LinkedList;
11:
12: /**
13: *
14: */
15: public class StateMachineRunner implements EventContext {
16: private final LinkedList events = new LinkedList();
17: private boolean scheduled = false;
18: private final Sink sink;
19: private final AbstractStateMachine stateMachine;
20:
21: public StateMachineRunner(AbstractStateMachine stateMachine,
22: Sink sink) {
23: this .sink = sink;
24: this .stateMachine = stateMachine;
25: }
26:
27: public synchronized int getEventsCount() {
28: return (events.size());
29: }
30:
31: public synchronized void start() {
32: stateMachine.start();
33: }
34:
35: public synchronized void pause() {
36: if (!stateMachine.isPaused()) {
37: stateMachine.pause();
38: }
39: }
40:
41: public synchronized boolean isPaused() {
42: return stateMachine.isPaused();
43: }
44:
45: public synchronized void resume() {
46: events.clear();
47: stateMachine.resume();
48: //scheduleIfNeeded();
49: }
50:
51: public void run() {
52: OOOProtocolEvent pe = null;
53: synchronized (this ) {
54: // NOTE: in some cases, our message q gets out of synch with this event q.
55: // in this case check if empty.
56: // this should simplified.
57: if (events.isEmpty())
58: return;
59: pe = (OOOProtocolEvent) events.removeFirst();
60: }
61: pe.execute(stateMachine);
62: synchronized (this ) {
63: scheduled = false;
64: scheduleIfNeeded();
65: }
66: }
67:
68: public synchronized void addEvent(OOOProtocolEvent event) {
69: events.addLast(event);
70: scheduleIfNeeded();
71: }
72:
73: private synchronized void scheduleIfNeeded() {
74: if (!scheduled && !events.isEmpty() && !stateMachine.isPaused()) {
75: scheduled = true;
76: sink.add(this );
77: }
78: }
79:
80: public synchronized void reset() {
81: events.clear();
82: stateMachine.reset();
83: }
84: }
|