1 18 package org.apache.activemq.thread; 19 20 27 final public class Valve { 28 29 private final Object mutex = new Object (); 30 private boolean on; 31 private int turningOff=0; 32 private int usage=0; 33 34 public Valve(boolean on) { 35 this.on = on; 36 } 37 38 42 public void turnOn() throws InterruptedException { 43 synchronized(mutex) { 44 while( on ) { 45 mutex.wait(); 46 } 47 on=true; 48 mutex.notifyAll(); 49 } 50 } 51 52 boolean isOn() { 53 synchronized(mutex) { 54 return on; 55 } 56 } 57 58 64 public void turnOff() throws InterruptedException { 65 synchronized(mutex) { 66 try { 67 ++turningOff; 68 while( usage > 0 || !on) { 69 mutex.wait(); 70 } 71 on=false; 72 mutex.notifyAll(); 73 } finally { 74 --turningOff; 75 } 76 } 77 } 78 79 85 public void increment() throws InterruptedException { 86 synchronized(mutex) { 87 while( turningOff>0 || !on ) { 89 mutex.wait(); 90 } 91 usage++; 92 } 93 } 94 95 98 public void decrement() { 99 synchronized(mutex) { 100 usage--; 101 if( turningOff>0 && usage < 1 ) { 102 mutex.notifyAll(); 103 } 104 } 105 } 106 107 } 108 | Popular Tags |