KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tc > net > protocol > delivery > StateMachineRunner


1 /*
2  * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
3  */

4 package com.tc.net.protocol.delivery;
5
6 import com.tc.async.api.EventContext;
7 import com.tc.async.api.Sink;
8
9 import java.util.LinkedList JavaDoc;
10
11 /**
12  *
13  */

14 public class StateMachineRunner implements EventContext {
15   private final LinkedList JavaDoc events = new LinkedList JavaDoc();
16   private boolean scheduled = false;
17   private final Sink sink;
18   private final AbstractStateMachine stateMachine;
19
20   public StateMachineRunner(AbstractStateMachine stateMachine, Sink sink) {
21     this.sink = sink;
22     this.stateMachine = stateMachine;
23   }
24
25   public synchronized void start() {
26     stateMachine.start();
27   }
28
29   public synchronized void pause() {
30     if (! stateMachine.isPaused()) {
31       stateMachine.pause();
32     }
33   }
34
35   public synchronized void resume() {
36     stateMachine.resume();
37     scheduleIfNeeded();
38   }
39
40   public void run() {
41     OOOProtocolEvent pe = null;
42     synchronized (this) {
43       pe = (OOOProtocolEvent) events.removeFirst();
44     }
45     pe.execute(stateMachine);
46     synchronized (this) {
47       scheduled = false;
48       scheduleIfNeeded();
49     }
50   }
51
52   public synchronized void addEvent(OOOProtocolEvent event) {
53     events.addLast(event);
54     scheduleIfNeeded();
55   }
56
57   private synchronized void scheduleIfNeeded() {
58     if (!scheduled && !events.isEmpty() && ! stateMachine.isPaused()) {
59       scheduled = true;
60       sink.add(this);
61     }
62   }
63 }
Popular Tags