1 10 package org.mmbase.util; 11 12 import org.mmbase.util.logging.Logger; 13 import org.mmbase.util.logging.Logging; 14 32 public class DijkstraSemaphore { 33 34 private static final Logger log = Logging.getLoggerInstance(DijkstraSemaphore.class); 35 36 private int count; 37 private int maxCount; 38 private Object starvationLock = new Object (); 39 40 45 public DijkstraSemaphore(int pMaxCount) { 46 this(pMaxCount, pMaxCount); 47 } 48 49 56 public DijkstraSemaphore(int pMaxCount, int pInitialCount) { 57 count = pInitialCount; 58 maxCount = pMaxCount; 59 } 60 61 68 public synchronized void acquire() throws InterruptedException { 69 while (count == 0) { 72 long startwait = 0; 73 if (log.isDebugEnabled()) { 74 startwait = System.currentTimeMillis(); 75 } 76 wait(); 77 if (startwait != 0) { 78 log.debug("Waited " + (System.currentTimeMillis() - startwait) + " ms for a resource"); 79 } 80 } 81 count--; 82 synchronized (starvationLock) { 83 if (count == 0) { 84 starvationLock.notify(); 85 } 86 } 87 } 88 89 94 public synchronized boolean tryAcquire() { 95 if (count != 0) { 96 count--; 97 synchronized (starvationLock) { 98 if (count == 0) { 99 starvationLock.notify(); 100 } 101 } 102 return true; 103 } 104 else { 105 return false; 106 } 107 } 108 109 117 public synchronized void release() { 118 count++; 119 if (count > maxCount) { 120 count = maxCount; 121 } 122 notify(); 123 } 124 125 131 public synchronized void release(int pCount) { 132 while (count < maxCount && pCount != 0){ 133 release(); 134 pCount --; 135 } 136 } 137 138 144 public synchronized void acquireAll() throws InterruptedException { 145 while(count != 0){ 146 acquire(); 147 } 148 } 149 150 156 public synchronized void releaseAll() { 157 release(maxCount); 158 } 159 160 168 public void starvationCheck() throws InterruptedException { 169 synchronized (starvationLock) { 170 if (count != 0) { 171 starvationLock.wait(); 172 } 173 } 174 } 175 } 176 177 | Popular Tags |