1 4 package dso.concurrency; 5 6 import java.util.ArrayList ; 7 import java.util.List ; 8 9 12 public class ConcurrencyTester { 13 14 private int listSize = 0; 15 private List trades = new ArrayList (); 16 private Shuffler shuffler; 17 private List clientSet = new ArrayList (); 18 19 public ConcurrencyTester(int listSize) { 20 initializeList(listSize); 21 shuffler = new Shuffler(listSize); 22 } 23 24 private void initializeList(int size) { 25 listSize = size; 26 synchronized (trades) { 27 if (trades.size() != listSize) { 28 trades.clear(); 29 for (int i = 0; i < listSize; i++) { 30 trades.add(new SimpleTrade()); 31 } 32 } 33 } 34 } 35 36 private void clear() { 37 synchronized (trades) { 38 trades.clear(); 39 } 40 } 41 42 public void awaitClients(int numClients, boolean verbose) { 43 synchronized (clientSet) { 44 clientSet.add(new Object ()); 45 clientSet.notifyAll(); 46 while (clientSet.size() != numClients && clientSet.size() != 0) { 47 if (verbose) { 48 System.out.println("Waiting for " + (numClients - clientSet.size()) + " to start..."); 49 } 50 try { 51 clientSet.wait(); 52 } catch (InterruptedException ie) { 53 } 55 } 56 clientSet.clear(); 57 } 58 } 59 60 public void incrementInRandomOrder() { 61 int[] incrementOrder = shuffler.shuffleOrder(); 62 for (int i = 0; i < incrementOrder.length; i++) { 63 SimpleTrade st; 64 synchronized (trades) { 65 st = (SimpleTrade) trades.get(incrementOrder[i]); 66 } 67 st.incrementCounter(); 68 } 69 } 70 71 public static void main(String [] args) { 72 if (args.length != 3) { 73 System.out.println("usage: java dso.concurrency.ConcurrencyTester <rounds> <listsize> <numclients>"); 74 System.exit(1); 75 } 76 int rounds = Integer.parseInt(args[0]); 77 int listSize = Integer.parseInt(args[1]); 78 int numClients = Integer.parseInt(args[2]); 79 80 ConcurrencyTester ct = new ConcurrencyTester(listSize); 81 ct.awaitClients(numClients, true); 82 ct.updateValues(rounds); 83 ct.awaitClients(numClients, false); 84 ct.printResults(); 85 ct.awaitClients(numClients, false); 86 ct.clear(); 87 } 88 89 private synchronized void printResults() { 90 for (int i = 0; i < listSize; i++) { 91 System.out.println("Final Value of position " + i + " is " + ((SimpleTrade) trades.get(i)).getCounter()); 92 } 93 } 94 95 private void updateValues(int rounds) { 96 for (int i = 0; i < rounds; i++) { 97 incrementInRandomOrder(); 98 } 99 } 100 101 } 102 | Popular Tags |