1 50 package org.apache.avalon.excalibur.concurrent; 51 52 65 public class Semaphore 66 implements Sync 67 { 68 private long m_tokens; 69 70 76 public Semaphore( final long tokens ) 77 { 78 m_tokens = tokens; 79 } 80 81 public synchronized void acquire() 82 throws InterruptedException 83 { 84 if( Thread.interrupted() ) throw new InterruptedException (); 86 87 while( 0 >= m_tokens ) 89 { 90 wait(); 91 } 92 m_tokens--; 93 } 94 95 public synchronized void release() 96 { 97 m_tokens++; 98 notify(); 99 } 100 101 public synchronized boolean attempt( final long msecs ) 102 throws InterruptedException 103 { 104 if( Thread.interrupted() ) throw new InterruptedException (); 105 106 if( m_tokens > 0 ) 107 { 108 m_tokens--; 109 return true; 110 } 111 else 112 { 113 final long start = System.currentTimeMillis(); 114 long wait = msecs; 115 116 while( wait > 0 ) 117 { 118 wait( wait ); 119 120 if( m_tokens > 0 ) 121 { 122 m_tokens--; 123 return true; 124 } 125 else 126 { 127 wait = msecs - ( System.currentTimeMillis() - start ); 128 } 129 } 130 131 return false; 132 } 133 } 134 } 135 | Popular Tags |