1 17 18 package org.apache.avalon.fortress.impl.handler; 19 20 import java.util.Collections ; 21 import java.util.Iterator ; 22 import java.util.LinkedList ; 23 import java.util.List ; 24 25 26 34 public final class PerThreadComponentHandler 35 extends AbstractComponentHandler 36 { 37 private ThreadLocalComponent m_instance; 38 private List m_instances; 39 40 public void initialize() 41 throws Exception 42 { 43 super.initialize(); 44 m_instance = new ThreadLocalComponent( this ); 45 m_instances = Collections.synchronizedList(new LinkedList ()); 46 } 47 48 51 protected Object doGet() 52 throws Exception 53 { 54 final Object instance = m_instance.get(); 55 if ( null == instance ) 56 { 57 throw new IllegalStateException ( "Instance is unavailable" ); 58 } 59 60 return instance; 61 } 62 63 protected void doDispose() 64 { 65 Iterator it = m_instances.iterator(); 66 while (it.hasNext()) 67 { 68 disposeComponent( it.next() ); 69 it.remove(); 70 } 71 m_instance = null; 72 m_instances = null; 73 } 74 75 private static final class ThreadLocalComponent 76 extends ThreadLocal 77 { 78 private final PerThreadComponentHandler m_handler; 79 80 protected ThreadLocalComponent( final PerThreadComponentHandler handler ) 81 { 82 m_handler = handler; 83 } 84 85 protected Object initialValue() 86 { 87 try 88 { 89 Object component = m_handler.newComponent(); 90 m_handler.m_instances.add(component); 91 return component; 92 } 93 catch ( final Exception e ) 94 { 95 return null; 96 } 97 } 98 } 99 } 100 | Popular Tags |