1 28 29 package org.apache.commons.transaction.util; 30 31 39 public class TurnBarrier { 40 41 public static final long DEFAULT_TIMEOUT = Long.MAX_VALUE; 42 43 protected final String name; 44 45 protected int currentNumber; 46 47 protected final int startNumber; 48 49 protected final long timeout; 50 51 protected LoggerFacade logger; 52 53 59 public TurnBarrier(String name, LoggerFacade logger) { 60 this(name, DEFAULT_TIMEOUT, logger); 61 } 62 63 70 public TurnBarrier(String name, long timeout, LoggerFacade logger) { 71 this(name, timeout, logger, 0); 72 } 73 74 82 public TurnBarrier(String name, long timeout, LoggerFacade logger, int startTurn) { 83 this.name = name; 84 this.timeout = timeout; 85 this.logger = logger; 86 this.startNumber = startTurn; 87 this.currentNumber = startTurn; 88 } 89 90 97 public synchronized void waitForTurn(int turnNumber) throws InterruptedException , 98 RuntimeException { 99 if (turnNumber > currentNumber) { 100 long started = System.currentTimeMillis(); 101 for (long remaining = timeout; remaining > 0 && turnNumber > currentNumber; remaining = timeout 102 - (System.currentTimeMillis() - started)) { 103 wait(remaining); 104 } 105 } 106 if (turnNumber > currentNumber) { 107 throw new RuntimeException ("Timed out while waiting for our turn"); 108 } 109 } 110 111 116 public synchronized void signalTurn(int turnNumber) { 117 currentNumber = turnNumber; 118 notifyAll(); 119 } 120 121 125 public synchronized void reset() { 126 signalTurn(startNumber); 127 } 128 } | Popular Tags |