1 8 package org.apache.avalon.excalibur.pool; 9 10 import org.apache.avalon.framework.activity.Disposable; 11 import org.apache.avalon.excalibur.collections.Buffer; 12 import org.apache.avalon.excalibur.collections.FixedSizeBuffer; 13 import org.apache.avalon.excalibur.concurrent.Mutex; 14 15 23 public final class FixedSizePool 24 implements Pool, Disposable 25 { 26 private boolean m_disposed = false; 27 private final Buffer m_buffer; 28 private final ObjectFactory m_factory; 29 private final Mutex m_mutex = new Mutex(); 30 31 public FixedSizePool( ObjectFactory factory, int size ) 32 throws Exception 33 { 34 m_buffer = new FixedSizeBuffer( size ); 35 m_factory = factory; 36 37 for ( int i = 0; i < size; i++ ) 38 { 39 m_buffer.add( m_factory.newInstance() ); 40 } 41 } 42 43 public Poolable get() 44 { 45 if ( m_disposed ) 46 { 47 throw new IllegalStateException ( "Cannot get an object from a disposed pool" ); 48 } 49 50 Poolable object = null; 51 52 try 53 { 54 m_mutex.acquire(); 55 object = (Poolable) m_buffer.remove(); 56 } 57 catch ( InterruptedException ie ) 58 { 59 } 61 finally 62 { 63 m_mutex.release(); 64 } 65 66 return object; 67 } 68 69 public void put( Poolable object ) 70 { 71 if ( m_disposed ) 72 { 73 try 74 { 75 m_factory.decommission( object ); 76 } 77 catch ( Exception e ) 78 { 79 } 81 } 82 else 83 { 84 try 85 { 86 m_mutex.acquire(); 87 m_buffer.add( object ); 88 } 89 catch ( InterruptedException e ) 90 { 91 } 93 finally 94 { 95 m_mutex.release(); 96 } 97 } 98 } 99 100 public void dispose() 101 { 102 m_disposed = true; 103 104 try 105 { 106 m_mutex.acquire(); 107 108 while ( ! m_buffer.isEmpty() ) 109 { 110 try 111 { 112 m_factory.decommission( m_buffer.remove() ); 113 } 114 catch ( Exception e ) 115 { 116 } 118 } 119 } 120 catch ( InterruptedException ie ) 121 { 122 } 124 finally 125 { 126 m_mutex.release(); 127 } 128 } 129 } 130 131 | Popular Tags |