01: /*
02: * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
03: */
04: package com.tctest.runner;
05:
06: import com.tc.util.concurrent.ThreadUtil;
07:
08: import java.util.HashMap;
09: import java.util.Iterator;
10: import java.util.Map;
11:
12: /**
13: *
14: */
15: public class TransparentAppCoordinator {
16: private final String globalId;
17: private final int participantCount;
18: private final Map participants = new HashMap();
19: private final boolean print = false;
20:
21: public TransparentAppCoordinator(String globalId,
22: int participantCount) {
23: this .globalId = globalId;
24: this .participantCount = participantCount;
25: }
26:
27: public String getGlobalId() {
28: return this .globalId;
29: }
30:
31: public int getParticipantCount() {
32: return this .participantCount;
33: }
34:
35: public void moveToStageAndWait(int stage) {
36: try {
37: moveToStage(stage);
38: while (true) {
39: if (allNodesInOrBeyondStage(stage))
40: return;
41: ThreadUtil.reallySleep(1000);
42: println("Waiting");
43: }
44: } finally {
45: synchronized (participants) {
46: println("Done waiting:" + participants + " stage: "
47: + stage);
48: }
49: }
50: }
51:
52: public void moveToStage(int stage) {
53: synchronized (participants) {
54: participants.put("" + globalId, new Integer(stage));
55: }
56: }
57:
58: public boolean allNodesInOrBeyondStage(int stage) {
59: synchronized (participants) {
60: println("participants: " + participants
61: + ", participantCount: " + this .participantCount);
62: if (participants.size() != this .participantCount)
63: return false;
64: for (Iterator i = participants.keySet().iterator(); i
65: .hasNext();) {
66: int testStage = ((Integer) participants.get(i.next()))
67: .intValue();
68: if (testStage < stage)
69: return false;
70: }
71: }
72: return true;
73: }
74:
75: private void println(String line) {
76: if (print) {
77: System.out.println(Thread.currentThread() + ": " + line);
78: }
79: }
80: }
|