001: /*
002: * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
003: */
004: package dso.concurrency;
005:
006: import java.util.ArrayList;
007: import java.util.List;
008:
009: /**
010: * Created by Alan Brown Date: May 17, 2005 Time: 1:55:05 PM
011: */
012: public class ConcurrencyTester {
013:
014: private int listSize = 0;
015: private List trades = new ArrayList();
016: private Shuffler shuffler;
017: private List clientSet = new ArrayList();
018:
019: public ConcurrencyTester(int listSize) {
020: initializeList(listSize);
021: shuffler = new Shuffler(listSize);
022: }
023:
024: private void initializeList(int size) {
025: listSize = size;
026: synchronized (trades) {
027: if (trades.size() != listSize) {
028: trades.clear();
029: for (int i = 0; i < listSize; i++) {
030: trades.add(new SimpleTrade());
031: }
032: }
033: }
034: }
035:
036: private void clear() {
037: synchronized (trades) {
038: trades.clear();
039: }
040: }
041:
042: public void awaitClients(int numClients, boolean verbose) {
043: synchronized (clientSet) {
044: clientSet.add(new Object());
045: clientSet.notifyAll();
046: while (clientSet.size() != numClients
047: && clientSet.size() != 0) {
048: if (verbose) {
049: System.out.println("Waiting for "
050: + (numClients - clientSet.size())
051: + " to start...");
052: }
053: try {
054: clientSet.wait();
055: } catch (InterruptedException ie) {
056: // Ignore
057: }
058: }
059: clientSet.clear();
060: }
061: }
062:
063: public void incrementInRandomOrder() {
064: int[] incrementOrder = shuffler.shuffleOrder();
065: for (int i = 0; i < incrementOrder.length; i++) {
066: SimpleTrade st;
067: synchronized (trades) {
068: st = (SimpleTrade) trades.get(incrementOrder[i]);
069: }
070: st.incrementCounter();
071: }
072: }
073:
074: public static void main(String[] args) {
075: if (args.length != 3) {
076: System.out
077: .println("usage: java dso.concurrency.ConcurrencyTester <rounds> <listsize> <numclients>");
078: System.exit(1);
079: }
080: int rounds = Integer.parseInt(args[0]);
081: int listSize = Integer.parseInt(args[1]);
082: int numClients = Integer.parseInt(args[2]);
083:
084: ConcurrencyTester ct = new ConcurrencyTester(listSize);
085: ct.awaitClients(numClients, true);
086: ct.updateValues(rounds);
087: ct.awaitClients(numClients, false);
088: ct.printResults();
089: ct.awaitClients(numClients, false);
090: ct.clear();
091: }
092:
093: private synchronized void printResults() {
094: for (int i = 0; i < listSize; i++) {
095: System.out.println("Final Value of position " + i + " is "
096: + ((SimpleTrade) trades.get(i)).getCounter());
097: }
098: }
099:
100: private void updateValues(int rounds) {
101: for (int i = 0; i < rounds; i++) {
102: incrementInRandomOrder();
103: }
104: }
105:
106: }
|