KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tctest > runner > TransparentAppCoordinator


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.tctest.runner;
5
6 import com.tc.util.concurrent.ThreadUtil;
7
8 import java.util.HashMap JavaDoc;
9 import java.util.Iterator JavaDoc;
10 import java.util.Map JavaDoc;
11
12 /**
13  *
14  */

15 public class TransparentAppCoordinator {
16   private final String JavaDoc globalId;
17   private final int participantCount;
18   private final Map JavaDoc participants = new HashMap JavaDoc();
19   private final boolean print = false;
20
21   public TransparentAppCoordinator(String JavaDoc globalId, int participantCount) {
22     this.globalId = globalId;
23     this.participantCount = participantCount;
24   }
25
26   public String JavaDoc getGlobalId() {
27     return this.globalId;
28   }
29
30   public int getParticipantCount() {
31     return this.participantCount;
32   }
33
34   public void moveToStageAndWait(int stage) {
35     try {
36       moveToStage(stage);
37       while (true) {
38         if (allNodesInOrBeyondStage(stage)) return;
39         ThreadUtil.reallySleep(1000);
40         println("Waiting");
41       }
42     } finally {
43       synchronized (participants) {
44         println("Done waiting:" + participants + " stage: " + stage);
45       }
46     }
47   }
48
49   public void moveToStage(int stage) {
50     synchronized (participants) {
51       participants.put("" + globalId, new Integer JavaDoc(stage));
52     }
53   }
54
55   public boolean allNodesInOrBeyondStage(int stage) {
56     synchronized (participants) {
57       println("participants: " + participants + ", participantCount: " + this.participantCount);
58       if (participants.size() != this.participantCount) return false;
59       for (Iterator JavaDoc i = participants.keySet().iterator(); i.hasNext();) {
60         int testStage = ((Integer JavaDoc) participants.get(i.next())).intValue();
61         if (testStage < stage) return false;
62       }
63     }
64     return true;
65   }
66
67   private void println(String JavaDoc line) {
68     if (print) {
69       System.out.println(Thread.currentThread() + ": " + line);
70     }
71   }
72 }
Popular Tags