1 17 18 package org.apache.avalon.cornerstone.threads.tutorial; 19 20 import org.apache.avalon.framework.logger.AbstractLogEnabled; 21 import org.apache.avalon.framework.service.Serviceable; 22 import org.apache.avalon.framework.service.ServiceManager; 23 import org.apache.avalon.framework.service.ServiceException; 24 import org.apache.avalon.framework.activity.Initializable; 25 import org.apache.avalon.framework.activity.Disposable; 26 27 import org.apache.excalibur.thread.ThreadControl; 28 import org.apache.excalibur.thread.ThreadPool; 29 30 import org.apache.avalon.cornerstone.services.threads.ThreadManager; 31 32 39 public class ThreadConsumer extends AbstractLogEnabled implements 40 Serviceable, Initializable, Disposable 41 { 42 45 private ServiceManager m_manager; 46 47 50 private ThreadManager m_threads; 51 52 55 private ThreadPool m_pool; 56 57 60 private ThreadControl m_control; 61 62 63 73 public void service( ServiceManager manager ) throws ServiceException 74 { 75 m_manager = manager; 76 getLogger().info( "aquiring cornerstone threads service" ); 77 m_threads = (ThreadManager) m_manager.lookup( "threads" ); 78 } 79 80 85 public void initialize() throws Exception 86 { 87 getLogger().info( "initialization" ); 88 89 93 m_pool = m_threads.getDefaultThreadPool(); 94 95 99 Counter counter = new Counter(); 100 counter.enableLogging( getLogger().getChildLogger( "counter" ) ); 101 102 106 m_control = m_pool.execute( counter ); 107 } 108 109 113 public void dispose() 114 { 115 getLogger().info( "disposal" ); 116 117 if( ( m_control != null ) && !m_control.isFinished() ) 118 { 119 123 getLogger().info( "disposal invoked while child thread active" ); 124 m_control.interrupt(); 125 126 131 while( !m_control.isFinished() ) 132 { 133 getLogger().info( "waiting for child" ); 134 try 135 { 136 Thread.sleep( 1000 ); 137 } 138 catch( InterruptedException ie ) 139 { 140 } 142 } 143 } 144 145 149 if( ( m_control != null ) && ( m_control.getThrowable() != null ) ) 150 { 151 getLogger().warn( 152 "thread terminated with exception condition", 153 m_control.getThrowable() ); 154 } 155 156 if( m_pool != null ) 157 { 158 if( m_pool instanceof Disposable ) 159 { 160 ((Disposable)m_pool).dispose(); 161 } 162 m_pool = null; 163 } 164 165 m_manager.release( m_threads ); 166 167 m_control = null; 168 m_threads = null; 169 m_manager = null; 170 171 getLogger().info( "disposed" ); 172 } 173 } 174 175 | Popular Tags |