1 2 9 package org.apache.avalon.excalibur.pool; 10 11 import org.apache.avalon.framework.activity.Disposable; 12 import org.apache.avalon.excalibur.collections.Buffer; 13 import org.apache.avalon.excalibur.collections.VariableSizeBuffer; 14 import org.apache.avalon.excalibur.concurrent.Mutex; 15 16 24 public final class VariableSizePool 25 implements Pool, Disposable, ManagablePool 26 { 27 private boolean m_disposed = false; 28 private final Buffer m_buffer; 29 private final ObjectFactory m_factory; 30 private final Mutex m_mutex = new Mutex(); 31 private final long m_key; 32 33 36 public VariableSizePool( ObjectFactory factory, int size ) 37 throws Exception 38 { 39 this( factory, size, -1 ); 40 } 41 42 45 public VariableSizePool( ObjectFactory factory, int size, long key ) 46 throws Exception 47 { 48 m_buffer = new VariableSizeBuffer( size ); 49 m_factory = factory; 50 m_key = key; 51 52 for ( int i = 0; i < size; i++ ) 53 { 54 m_buffer.add( m_factory.newInstance() ); 55 } 56 } 57 58 public Poolable get() 59 { 60 if ( m_disposed ) 61 { 62 throw new IllegalStateException ( "Cannot get an object from a disposed pool" ); 63 } 64 65 return (Poolable) m_buffer.remove(); 66 } 67 68 public void put( Poolable object ) 69 { 70 if ( m_disposed ) 71 { 72 try 73 { 74 m_factory.decommission( object ); 75 } 76 catch ( Exception e ) 77 { 78 } 80 } 81 else 82 { 83 m_buffer.add( object ); 84 } 85 } 86 87 public void dispose() 88 { 89 m_disposed = true; 90 91 while ( ! m_buffer.isEmpty() ) 92 { 93 try 94 { 95 m_factory.decommission( m_buffer.remove() ); 96 } 97 catch ( Exception e ) 98 { 99 } 101 } 102 } 103 104 public void shrink( final int byNum, final long key ) 105 throws IllegalAccessException 106 { 107 if ( m_key < 0 || m_key != key ) 108 { 109 throw new IllegalAccessException (); 110 } 111 112 try 113 { 114 m_mutex.acquire(); 115 116 final int num = Math.min( byNum, m_buffer.size() ); 117 118 for ( int i = 0; i < num; i++ ) 119 { 120 m_factory.decommission( m_buffer.remove() ); 121 } 122 } 123 catch ( Exception e ) 124 { 125 } 127 finally 128 { 129 m_mutex.release(); 130 } 131 } 132 133 public void grow( final int byNum, final long key ) 134 throws IllegalAccessException 135 { 136 if ( m_key < 0 || m_key != key ) 137 { 138 throw new IllegalAccessException (); 139 } 140 141 try 142 { 143 m_mutex.acquire(); 144 145 for ( int i = 0; i < byNum; i++ ) 146 { 147 m_buffer.add( m_factory.newInstance() ); 148 } 149 } 150 catch ( Exception ie ) 151 { 152 } 154 finally 155 { 156 m_mutex.release(); 157 } 158 } 159 160 public int size( final long key ) 161 throws IllegalAccessException 162 { 163 if ( m_key < 0 || m_key != key ) 164 { 165 throw new IllegalAccessException (); 166 } 167 168 return m_buffer.size(); 169 } 170 } 171 | Popular Tags |