1 50 package org.apache.avalon.excalibur.concurrent; 51 52 65 public class DijkstraSemaphore 66 { 67 private int m_count; 68 private int m_maxCount; 69 private Object m_starvationLock = new Object (); 70 71 77 public DijkstraSemaphore( int maxCount ) 78 { 79 this( maxCount, maxCount ); 80 } 81 82 91 public DijkstraSemaphore( int maxCount, int initialCount ) 92 { 93 m_count = initialCount; 94 m_maxCount = maxCount; 95 } 96 97 105 public void acquire() 106 throws InterruptedException 107 { 108 synchronized( this ) 109 { 110 while( m_count == 0 ) 113 { 114 wait(); 115 } 116 m_count--; 117 synchronized( m_starvationLock ) 118 { 119 if( m_count == 0 ) 120 { 121 m_starvationLock.notify(); 122 } 123 } 124 } 125 } 126 127 133 public boolean tryAcquire() 134 { 135 synchronized( this ) 136 { 137 if( m_count != 0 ) 138 { 139 m_count--; 140 synchronized( m_starvationLock ) 141 { 142 if( m_count == 0 ) 143 { 144 m_starvationLock.notify(); 145 } 146 } 147 return true; 148 } 149 else 150 { 151 return false; 152 } 153 } 154 } 155 156 166 public void release() 167 { 168 synchronized( this ) 169 { 170 m_count++; 171 if( m_count > m_maxCount ) 172 { 173 m_count = m_maxCount; 174 } 175 notify(); 176 } 177 } 178 179 187 public void release( int count ) 188 { 189 synchronized( this ) 190 { 191 if( m_count + count > m_maxCount ) 192 { 193 m_count = m_maxCount; 194 } 195 else 196 { 197 m_count += count; 198 } 199 notifyAll(); 200 } 201 } 202 203 211 public void acquireAll() 212 throws InterruptedException 213 { 214 synchronized( this ) 215 { 216 for( int index = 0; index < m_maxCount; index++ ) 217 { 218 acquire(); 219 } 220 } 221 } 222 223 230 public void releaseAll() 231 { 232 synchronized( this ) 233 { 234 release( m_maxCount ); 235 notifyAll(); 236 } 237 } 238 239 248 public void starvationCheck() 249 throws InterruptedException 250 { 251 synchronized( m_starvationLock ) 252 { 253 if( m_count != 0 ) 254 { 255 m_starvationLock.wait(); 256 } 257 } 258 } 259 } 260 | Popular Tags |