1 16 17 package org.springframework.util; 18 19 import java.io.IOException ; 20 import java.io.ObjectInputStream ; 21 import java.io.Serializable ; 22 23 import org.apache.commons.logging.Log; 24 import org.apache.commons.logging.LogFactory; 25 26 46 public abstract class ConcurrencyThrottleSupport implements Serializable { 47 48 51 public static final int UNBOUNDED_CONCURRENCY = -1; 52 53 56 public static final int NO_CONCURRENCY = 0; 57 58 59 60 protected transient Log logger = LogFactory.getLog(getClass()); 61 62 private transient Object monitor = new Object (); 63 64 private int concurrencyLimit = UNBOUNDED_CONCURRENCY; 65 66 private int concurrencyCount = 0; 67 68 69 78 public void setConcurrencyLimit(int concurrencyLimit) { 79 this.concurrencyLimit = concurrencyLimit; 80 } 81 82 85 public int getConcurrencyLimit() { 86 return this.concurrencyLimit; 87 } 88 89 94 public boolean isThrottleActive() { 95 return (this.concurrencyLimit > 0); 96 } 97 98 99 104 protected void beforeAccess() { 105 if (this.concurrencyLimit == NO_CONCURRENCY) { 106 throw new IllegalStateException ( 107 "Currently no invocations allowed - concurrency limit set to NO_CONCURRENCY"); 108 } 109 if (this.concurrencyLimit > 0) { 110 boolean debug = logger.isDebugEnabled(); 111 synchronized (this.monitor) { 112 while (this.concurrencyCount >= this.concurrencyLimit) { 113 if (debug) { 114 logger.debug("Concurrency count " + this.concurrencyCount + 115 " has reached limit " + this.concurrencyLimit + " - blocking"); 116 } 117 try { 118 this.monitor.wait(); 119 } 120 catch (InterruptedException ex) { 121 Thread.currentThread().interrupt(); 123 } 124 } 125 if (debug) { 126 logger.debug("Entering throttle at concurrency count " + this.concurrencyCount); 127 } 128 this.concurrencyCount++; 129 } 130 } 131 } 132 133 137 protected void afterAccess() { 138 if (this.concurrencyLimit >= 0) { 139 synchronized (this.monitor) { 140 this.concurrencyCount--; 141 if (logger.isDebugEnabled()) { 142 logger.debug("Returning from throttle at concurrency count " + this.concurrencyCount); 143 } 144 this.monitor.notify(); 145 } 146 } 147 } 148 149 150 154 private void readObject(ObjectInputStream ois) throws IOException , ClassNotFoundException { 155 ois.defaultReadObject(); 157 158 this.logger = LogFactory.getLog(getClass()); 160 this.monitor = new Object (); 161 } 162 163 } 164 | Popular Tags |